是一个xvalue的生命延长,当它被绑定到一个const lvalue引用? [英] Is an xvalue's lifetime extended when it is bound to a const lvalue reference?

查看:168
本文介绍了是一个xvalue的生命延长,当它被绑定到一个const lvalue引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写下面的代码:

#include <iostream>

using namespace std;

int main()
{
  cout << &(int &&)123 << endl;
  return 0;
}

然后 g ++

foo.cc: In function ‘int main()’:
foo.cc:7:20: error: taking address of xvalue (rvalue reference)

好,感谢

Ok, thanks to What are rvalues, lvalues, xvalues, glvalues, and prvalues? I get that an xvalue means that it's about to "expire", which makes sense. But now if I do this:

#include <iostream>

using namespace std;

int main()
{
  const int &x = (int &&)123;
  cout << &x << endl;
  return 0;
}

这个工作很好,会打印一个地址。所以,我有几个问题:

This "works" just fine and will print an address. So, I have a few questions:


  1. 如果值即将到期,为什么我可以参考呢?参考不会保留原始对象的活动(右?)。

  2. 这样的引用是否导致未定义的行为?例如。因为我们引用的对象可能已被破坏?

一般来说,有一种方法可以知道右值引用的生命周期?

In general is there a way to know the lifetime of an rvalue reference?

推荐答案

第12.2节第4-5段说,生命周期示例

Clause 12.2, paragraphs 4-5, says that the lifetime is extended in the second example


有两种上下文,其中临时表在与完整表达式结束不同的点处被销毁。 ...

There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. ...

第二个上下文是当引用绑定到临时时。引用绑定到的临时或临时(引用绑定的子对象的完整对象)在引用的生命周期内仍然存在,除了:

(这里没有任何例外适用) / p>

The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:
(none of the exceptions apply here)

这篇关于是一个xvalue的生命延长,当它被绑定到一个const lvalue引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆