Search code examples
c++stringtemporary

C++ temporary string lifetime


Apologies as I know similar-looking questions exist, but I'm still not totally clear. Is the following safe?

void copyStr(const char* s)
{
    strcpy(otherVar, s);
}

std::string getStr()
{
    return "foo";
}

main()
{
    copyStr(getStr().c_str());
}

A temporary std::string will store the return from getStr(), but will it live long enough for me to copy its C-string elsewhere? Or must I explicitly keep a variable for it, eg

std::string temp = getStr();
copyStr(temp.c_str());

Solution

  • Yes, it's safe. The temporary from getStr lives to the end of the full expression it appears in. That full expression is the copyStr call, so it must return before the temporary from getStr is destroyed. That's more than enough for you.