7
int&& rv = 10;
int& lv = rv; //no error

How is this possible?

Is this related to "reference collapsing rule"?

0

1 Answer 1

9
 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.

3
  • 1
    What happens if lv = 20;? Does rv hold unnamed variable assigned 10? (if not we assign on constant;)
    – ikh
    Jun 18, 2016 at 6:57
  • 1
    @ikh, if you mean 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.
    – Nawaz
    Jun 18, 2016 at 7:01
  • This answer is inaccurate. There are contexts such as the implicit-move in a return statement where rvalue references are considered to be xvalues, not lvalues. Oct 3 at 6:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.