Is the following C++ code well-formed?
void consumer(char const* p)
{
std::printf("%s", p);
}
std::string random_string_generator();
consumer(random_string_generator().c_str());
The problem I have with it is, that after creating the temporary std::string object and taking the c_str() pointer, nothing prevents the std::string object from getting destroyed, unless I’m wrong.
Is this code well-formed according to the standard? It does work, when I test with g++.
The pointer returned by
std::string::c_str()points to memorymaintained by the string object. It remains valid until a non-const
function is called on the string object, or the string object is
destructed. The string object you’re concerned about is a temporary.
It will be destructed at the end of the full expression, not before and
not after. In your case, the end of the full expression is after the
call to
consumer, so your code is safe. It wouldn’t be ifconsumersaved the pointer somewhere, with the idea of using it later.
The lifetime of temporaries has been strictly defined since C++98.
Before that, it varied, depending on the compiler, and the code you’ve
written wouldn’t have worked with g++ (pre 1995, roughly—g++
changed this almost immediately when the standards committee voted it).
(There wasn’t an
std::stringthen either, but the same issues affectany user written string class.)