为什么不能使用右值来初始化左值引用? [英] Why a rvalue cannot be used to initialize a lvalue reference?
问题描述
我可以做 const A&a = A()
和 A&&a = A()
,但是为什么我不能做 A&a = A()
?
I can do const A& a = A()
and A&& a = A()
, but why cannot I do 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.
这篇关于为什么不能使用右值来初始化左值引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!