But I run the example, there is no problem?
In fact, there's nothing wrong in the expression:
const char* cstr2 = ss.str().c_str();
The temporary (copy) object returned by ss.str()
will live long enough to let you get the underlying c-string with c_str()
.
Of course by the end of the expression you'll have a const char
pointer to an object that is probably deallocated (this depends heavily on the std::basic_string
implementation).
Therefore this is likely not a good idea. What you should do instead is:
auto x = ss.str();
const char* cstr2 = x.c_str();
The above code won't get you any trouble, since the returned value of str()
is now being copied/is not a temporary anymore, and the access to x.c_str()
will give you a valid pointer.