Home > Software engineering >  Named r-value reference binding vs assignment
Named r-value reference binding vs assignment

Time:01-20

A named rvalue reference in an lvalue, but it is an lvalue which can only bind to an rvalue, so:

int&& x = 5; // Ok because 5 is an rvalue
int&& y = x; // Error: You cannot bind an lvalue to an rvalue reference

Ok so then why is it that I can assign after binding the reference y to an rvalue?

int&& x = 5;
int&& y = 8;
y = x;  // Ok! This compiles!

x and y are both named rvalue references, so both are lvalues. Why can I bind an lvalue to an rvalue reference here, and why can I do it here but not in one line as shown in the first code snippet (int&& y = x;)?

CodePudding user response:

x and y are lvalues whose types are rvalue references. Those references are being bound to temporary ints, whose lifetimes are extended to match the lifetimes of the references.

The expression y = x does not rebind y's reference. That is not possible, a reference cannot be rebound. Instead, it reads the value of the int referred by x and then assigns that value to the int referred by y.

A reference is a reference, period. The type of reference dictates whether it refers to an existing lvalue variable or to a temporary rvalue variable. You can't have a reference to a reference, that is not a thing in C , which is why this code:

int&& x = 5;
int&& y = x;

doesn't compile.

But, this code:

int&& x = 5;
int&& y = std::move(x);
y = 7;

does compile, and works as you are expected (ie, assigning to y changes the value of the int that x refers to).

Online Demo

CodePudding user response:

In the second example you are not binding anything, that's just assignment, operator=.

  • Related