Search code examples
c++object-lifetime

Is the lifetime of the temporary string long enough here?


#include <cstdio>
#include <string>

std::string foo()
{
    return "Hello, World!";
}

int main()
{
    printf( "%s\n", foo().c_str() );
}

Solution

  • Yes, it is long enough. The string literal will cease to exist as the function returns, but at that point it has already been copied to a temporary std::string. That string will be copied (or will be created at the call site through copy elision) to the calling code. The resulting string will exist until the end of the expression, long enough to be passed to printf.