The following code works fine, but why is this correct code? Why is the "c_str()" pointer of the temporary returned by foo() valid? I thought, that this temporary is already destroyed when bar() is entered - but it doesn't seem to be like this. So, now I assume that the temporary returned by foo() will be destroyed after the call to bar() - is this correct? And why?
std::string foo() {
std::string out = something...;
return out;
}
void bar( const char* ccp ) {
// do something with the string..
}
bar( foo().c_str() );
c_str()
just returns a temporary pointer. Its lifetime says nothing about the lifetime of the data it points to. – Catacaustic