gimmeamilk
gimmeamilk

Reputation: 2120

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());

Upvotes: 4

Views: 5299

Answers (3)

user1585121
user1585121

Reputation:

You have to declare a temporary variable and assign to it the return result:

...
{
  std::string tmp = getStr();
  //tmp live
  ...
}
//tmp dead
...

A temporary var must have a name, and will live in the scope where it has been declared in.

Edit: it is safe, you pass it by copied value (your edit was heavy, and nullified my above answer. The above answer concern the first revision)

copyStr(getStr().c_str()); will pass the rvalue to copyStr()

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 545825

A temporary variable lives until the end of the full expression. So, in your example,

copyStr(getStr().c_str());

getStr()’s return value will live until the end of copyStr. It is therefore safe to access its value inside copyStr. Your code is potentially still unsafe, of course, because it doesn’t test that the buffer is big enough to hold the string.

Upvotes: 3

MSalters
MSalters

Reputation: 179961

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.

Upvotes: 5

Related Questions