简体   繁体   English

C ++临时字符串生存期

[英]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? 一个临时的std :: string将存储来自getStr()的返回值,但是它会活得足够长,以便我可以将其C字符串复制到别处吗? 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. 来自getStr的临时表达到它出现的完整表达式的末尾。该完整表达式是copyStr调用,因此必须在从getStr临时表之前返回。 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 . getStr()的返回值将一直存在,直到copyStr结束。 It is therefore safe to access its value inside copyStr . 因此,可以安全地在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. 临时var必须具有名称,并且将存在于已声明的范围内。

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() 将rvalue传递给copyStr()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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