cc
指向的數據的生命週期與其來自的字符串的生命週期相同(最好 - 如果修改字符串,它甚至更短)。
在你的情況下,foo()
的返回值是在cc
初始化結束時被破壞的臨時值。
爲了避免char *cc = foo().c_str()
編譯錯誤,你不應該強制轉換爲char*
,您應該切換到const char *cc
,因爲const char*
是什麼c_str()
回報。但是,這仍然不能解決主要問題。
最簡單的修復程序是:
printf("%s", foo().c_str()); // if you don't need the value again later
const string s = foo();
const char *cc = s.c_str(); // if you really want the pointer - since it's
// in the same scope as s, and s is const,
// the data lives as long as cc's in scope.
string s = foo();
printf("%s", s.c_str()); // if you don't store the pointer,
// you don't have to worry about it.
std::cout << foo(); // printf isn't bringing much to this party anyway.
+1提供正確的方法。 – 2011-05-10 08:22:09
完全正確; 'const引用'延長了一個右值的生命恰好是一個奇特的規則,'只''記住_value_也會。 (可能用C++ 11中的移動語義進行優化)。 – xtofl 2011-05-10 08:22:58
只要移動語義或RVO在工作中,使用值類型幾乎是等價的。但是引用阻止我們依賴編譯器優化。 – Xion 2011-05-10 08:26:52