standard c_str() problem in C++
-
I have craeted following kind of function in a class: void SetStr(string& s1, string& s2) { const char* s =(s1+s2).c_str(); cout<
-
I have craeted following kind of function in a class: void SetStr(string& s1, string& s2) { const char* s =(s1+s2).c_str(); cout<
The result of an expression is temporary, and it is destroyed an the and of the expression evaluation. In your first case, you are getting a temporary string as a result of
s1+s2
, whose buffer pointer is saved in s. After that, the expression finish, the temporary is destroyed, and so it is its buffer ands
is left dangling. You had been lucky in having printed nothing. accessing a deleted buffer can even result in a crash. In your second example, the temporary string resulting froms1+s2
is kept alive until the expression it belongs (cout<<(s1+s2).c_str()< ) is evaluated. Hence its buffer (renturned from `c_str()`) is still there at the time its pointer is given to `cout`. Your first sample works correctly if you retain the string: void SetStr(string& s1, string& s2) { string ss; //the place to store the result ss = s1+s2; //the result of s1+s2 is moved to ss, that survives the expression itself const char* s = ss.c_str(); //ss buffer pointer obtained cout << s << endl; //your original cout } 2 bugs found. > recompile ... 65534 bugs found. :doh:
-
The result of an expression is temporary, and it is destroyed an the and of the expression evaluation. In your first case, you are getting a temporary string as a result of
s1+s2
, whose buffer pointer is saved in s. After that, the expression finish, the temporary is destroyed, and so it is its buffer ands
is left dangling. You had been lucky in having printed nothing. accessing a deleted buffer can even result in a crash. In your second example, the temporary string resulting froms1+s2
is kept alive until the expression it belongs (cout<<(s1+s2).c_str()< ) is evaluated. Hence its buffer (renturned from `c_str()`) is still there at the time its pointer is given to `cout`. Your first sample works correctly if you retain the string: void SetStr(string& s1, string& s2) { string ss; //the place to store the result ss = s1+s2; //the result of s1+s2 is moved to ss, that survives the expression itself const char* s = ss.c_str(); //ss buffer pointer obtained cout << s << endl; //your original cout } 2 bugs found. > recompile ... 65534 bugs found. :doh:
-
Great answer. You miss an underscore in your sample code. --Carlo The Nitpick
Veni, vidi, vici.
But no applause for this guy standard c_str() problem in C++[^] :sigh: :-D but why do we have two forums on the same subject. Sorry I'm just outta the rock.
Starting to think people post kid pics in their profiles because that was the last time they were cute - Jeremy.