简体   繁体   English

使用右值引用延长临时项的生存期

[英]Extension of the lifetime of a temporary with an rvalue reference

According to another answer , an rvalue reference will not extend the lifetime of a temporary if the expression referring to it is an xvalue expression. 根据另一个答案 ,如果引用右值的表达式是xvalue表达式,则右值引用不会延长临时项的寿命。 Since std::move returns an rvalue reference, the expression of calling it is an xvalue and so the following results in an a dangling reference: 由于std::move返回一个右值引用,因此调用它的表达式是一个xvalue,因此以下结果将导致一个悬空引用:

int main()
{
  std::string&& danger = std::move(get_string());  // dangling reference !
  return 0;
}

That's fine. 没关系。 The std::move doesn't make sense here; std::move在这里没有意义; it is already an rvalue. 它已经是一个右值。

But here's where I'm drawing a blank. 但是,这是我要画空白的地方。 How is this different to passing an xvalue expression as an argument, completely standard use of std::move and rvalue references? 与将xvalue表达式作为参数传递,完全标准地使用std::move和rvalue引用有何不同?

void foo(const std::string& val);
// More efficient foo for temporaries:
void foo(std::string&& val);

int main()
{
  std::string s;
  foo(std::move(s)); // Give up s for efficiency
  return 0;
}

Is there a special rule for rvalue reference arguments that will extend the lifetime of a temporary regardless of whether it is an prvalue or xvalue? rvalue引用参数是否有一条特殊的规则,无论它是prvalue还是xvalue,都会延长临时对象的生存期? Or is the std::move calling expression only an xvalue because we passed it something that was already an rvalue? 还是std::move调用表达式只是一个xvalue,因为我们传递了已经是rvalue的东西? I don't think so because it returns an rvalue reference anyway, which is an xvalue. 我不这么认为,因为它无论如何都会返回一个右值引用,即xvalue。 I'm confused here. 我在这里很困惑。 I think I'm missing something silly. 我想我错过了一些愚蠢的事情。

Your second example is not passing a reference to a temporary, it's passing a reference to the variable s , which lasts until the end of main() . 您的第二个示例未传递对临时变量s引用,而是传递了对变量s的引用,该变量一直持续到main()的结尾。

If it were (eg foo(std::move(get_string())); ), then the temporary's lifetime lasts until the end of the full expression - after the function has returned. 如果是(例如foo(std::move(get_string())); )),则临时foo(std::move(get_string()));的生存期将一直持续到完整表达式的末尾-函数返回之后。 It's therefore quite safe to use it within foo . 因此,在foo使用它非常安全。 There is only a danger if foo stores a reference/pointer to its argument, and something else tries to use it later. 如果foo存储了对其参数的引用/指针,并且以后有其他尝试使用它,则只有危险。

这里不需要延长任何生存期:所讨论的对象会持续到main的末尾,也就是foo的末尾。

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

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