2011-05-10 32 views
5

我不知道,但是這不是爲我工作即時得到garbege值當我嘗試設置從函數返回的std字符串的char *值:如何設置從STD字符串的char *值(c_str())不工作

string foo() 
{ 
    string tmp ="dummy value"; 
    return tmp; 
} 

char* cc = (char *) foo().c_str(); // if i remove the casting im getting error 
// when i print the cc i get garbage 
printf("%s",cc); 

回答

13

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. 
9

foo的結果是,得到由char * cc = ...線的端部被破壞的暫時對象。在恆定的基準存儲它:

const string& cc = foo(); 
printf ("%s", cc.c_str()); 
+0

+1提供正確的方法。 – 2011-05-10 08:22:09

+0

完全正確; 'const引用'延長了一個右值的生命恰好是一個奇特的規則,'只''記住_value_也會。 (可能用C++ 11中的移動語義進行優化)。 – xtofl 2011-05-10 08:22:58

+0

只要移動語義或RVO在工作中,使用值類型幾乎是等價的。但是引用阻止我們依賴編譯器優化。 – Xion 2011-05-10 08:26:52

0

的代碼片段將調用未定義的行爲,因爲從呼叫創建的臨時std::string在表達的端部被破壞,但其被指向所述銷燬對象cc,仍然使用即使在那之後。

1

傳遞一個內存位置爲foo(),並有FOO修改:

void foo (string* _out_newStr) 
{ 
    _out_newStr->assign("dummy string"); //This is wrong -> _out_newStr = "dummy string"; 
    return; 
} 

然後,當您使用「c_str()」的字符串對象的函數將返回一個const char *值,正如已經指出的那樣。

+0

-1。錯...... – Nawaz 2011-05-10 08:24:33

+0

@Nawaz這有幫助...關心擴大?我也願意學習。 – Dennis 2011-05-10 08:27:55

+0

@ Dennis:'_out_newStr'是一個指向'std :: string'的指針,你怎麼能給它分配字符文字?你的代碼甚至不會編譯。 – Nawaz 2011-05-10 08:29:31

0

如何:

printf("%s", foo.c_str()); 

或者更好的,忘了使用字符指針。

+2

'std :: cout << foo()'如何? :d – Nawaz 2011-05-10 08:25:19