C++ temporary string lifetime

心不动则不痛 提交于 2019-12-10 15:53:46

问题


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

回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/24488122/c-temporary-string-lifetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!