int&& rv = 10;
int& lv = rv; //no error
How is this possible?
Is this related to "reference collapsing rule"?
int&& rv = 10;
int& lv = rv; //no error
First of all, a named object is never an rvalue. Second, since rv
is named object, it is not a rvalue, even though it binds to rvalue. Since rv
is lvalue, it can bind to lvalue without any problem.
Note that rvalue-ness is a property of an expression, not a variable. In the above example, an rvalue is created out of 10
and binds to rv
, which as I said, is lvalue.
lv = 20;
? Does rv
hold unnamed variable assigned 10
? (if not we assign on constant;)
int & lv = rv;
then lv = 20
. That is perfectly fine. However, if you meant int & lv = 20;
then that is invalid. You can think of &&
as magician which makes an lvalue to bind to rvalue expression. Since you can write &&
only in a declaration of the variable, you can write int && x = 20;
even though x
is a lvalue. There is another magician known as const
which makes an lvalue to bind to rvalue
as in : int const & lv = 20;
, which is valid.
return
statement where rvalue references are considered to be xvalues, not lvalues.
Oct 3 at 6:50