What you're doing is creating a temporary. That temporary exists in a scope determined by the compiler, such that it's long enough to satisfy the requirements of where it's going.
As soon as the statement const char* cstr2 = ss.str().c_str();
is complete, the compiler sees no reason to keep the temporary string around, and it's destroyed, and thus your const char *
is pointing to free'd memory.
Your statement string str(ss.str());
means that the temporary is used in the constructor for the string
variable str
that you've put on the local stack, and that stays around as long as you'd expect: until the end of the block, or function you've written. Therefore the const char *
within is still good memory when you try the cout
.