简体   繁体   中英

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM