2016-11-16 69 views
-2

以下示例中,我將fn作爲指向常量c字符串的常量指針。當我聲明並分配一個不相關的其他const指針給另一個常量c字符串時,原來的fn被修改。我一直試圖弄清楚爲什麼有一段時間,但看不到可能會導致這種情況的原因?爲什麼分配不相關的字符串會導致另一個字符串被修改?

輸出:

原始FN:sampleStrWithExtension

改性FN:randomStr2ModifiedFn

int main() { 
     std::string baseString = "sampleStr"; 
     std::string randomBaseString = "randomStr2"; 
     const char* const fn = (baseString + "WithExtension").c_str(); 
     std::cout << "Original fn: " << fn << std::endl; 
     const char* const variableNotFn = (randomBaseString + "ModifiedFn").c_str(); 
     std::cout << "Modified fn: " << fn << std::endl; 
     return 0; 
    } 
+1

'fn =(baseString +「WithExtension」)。c_str()'不是一個非常重要的任務。由表達式'baseString +'WithExtension「'創建的'string'對象在完成賦值後立即被銷燬,而變量'fn'指向未分配的內存,這可以在任何時候重用。 –

+4

'x.c_str()'的生命週期永遠不會超過'x'的生命週期。 – Angew

回答

8
const char* const fn = (baseString + "WithExtension").c_str(); 

這導致未定義的行爲。

baseString + "WithExtension" 

這會創建一個臨時對象std::stringstd::string上的+運算符會返回一個新的std::string,並且在此表達式的上下文中,返回的std::string將成爲臨時對象。 c_str()返回一個指向這個臨時對象的內部緩衝區的指針。

c_str()返回的指針僅在修改std::string之前有效,否則將被銷燬。在上述表達式的末尾,臨時對象被破壞。

稍後使用此指針會導致未定義的行爲。

+2

嚴格來說,這不是一個未定義的行爲。它只是一個指向沒有更多現有字符串的指針。未定義的行爲發生在您取消引用時 – valdo

相關問題