Around about 23/01/06 09:16, Jamie Kirkpatrick typed ...
std::string getString();
void f()
{
const char* p = getString().c_str();
// use p
}
Ok - this is what I meant. So what im seeing is correct OK, thats
good I guess! Is there something in the c++ spec i can point
people too to indicate that this is the case? An out of interest
- how come the destructor on string is not getting called so soon?
Nothing specific, it's more about understanding what's happening.
getString is returning a transient std::string which will only live
for the duration of the statement. You're calling .c_str() on
this, and that's fine. But at the end of the statement (after the
assignment) the string goes out of scope, its destructor is called
and the memory opinted to by the c_str() is invalid.
You have two alternatives; if getString() is accessing a long
term store you can guarantee will be around, you can make it return
a reference, maybe even a const ref. (which would be better), so
you're not accessing the transient but the original.
Alternatively, keep a copy yourself:
const std::string& getString();
void f()
{
const char* p = getString().c_str();
// use p
}
or
std::string getString();
void f()
{
const std::string s = getString;
const char* p = s().c_str();
// use p
}