简体   繁体   English

为什么不能使用右值初始化左值引用?

[英]Why a rvalue cannot be used to initialize a lvalue reference?

我可以做const A& a = A()A&& a = A() ,但是为什么我不能做A& a = A()

The rationale is that it rarely makes sense to mutate a temporary. 理由是,对临时变量进行突变几乎没有任何意义。 Any attempt to do so is likely to be a programming error rather than a deliberate decision. 这样做的任何尝试都可能是编程错误,而不是刻意的决定。

The prototypical example is as follows. 原型示例如下。 Assume binding to non-const reference is allowed. 假设允许绑定到非常量引用。

void foo(int& x, int& y); // sets x and y
int xx, yy;
foo(xx, yy); // xx and yy are set
// now make a small change...
void foo(long& x, long& y); // upgrade
int xx, yy; // forgot to change here 
foo(xx, yy); // silently breaks

While one does sometimes want to mutate a temporary, it's often for an entirely different reason from that of mutating an lvalue. 尽管有时确实希望对临时变量进行突变,但这通常是与对左值进行突变的原因完全不同的原因。 Rvalue references were invented to accommodate these cases. 发明了右值参考以适应这些情况。

By "initialising an lvalue reference" you refer to defining the lavalue which the reference is referring to from then on. 通过“初始化左值引用”,您指的是定义引用从此以后引用的左值。
So the lvalue-reference will propagate any access to the rvalue "initialisation". 因此,左值引用将传播对右值“初始化”的任何访问。
Ie you would attempt to access an rvalue-expression like an lvalue. 即,您将尝试访问类似于左值的右值表达式。
It is not possible in all cases to access an rvalue like an lvalue. 并非在所有情况下都可以访问左值(如左值)。

That is why. 这就是为什么。

An rvalue is a temporary - it's going to die soon. 右值是临时的-它将很快消失。 Creating a lvalue reference to such an object would be a recipe for disaster since the reference would become a dangling reference to a dead object very quickly. 对此类对象创建左值引用将是灾难的秘诀,因为该引用将很快成为对死对象的悬挂引用。

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

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