Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can i assign a value to a rvalue reference?

Tags:

I recently started learning about rvalues,lvalues, move semantics and I can't understands some conceps like rvalue refs .. why can I assign a value to a rvalue ref like : int&& x = 10;.. doesn't that mean that an rvalue ref is an lvalue(I tought that a rvalue ref is a rvalue)? If that is true ... what's the point of having rvalue references? If that is false then what is the difference between an rvalue ref and an lvalue ?

like image 750
Robert Avatar asked Jan 03 '21 17:01

Robert


People also ask

Can an rvalue be assigned to an lvalue?

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.

Can lvalue bind to rvalue reference?

An lvalue reference can bind to an lvalue, but not to an rvalue.

Can you modify an rvalue?

rvalue references have two properties that are useful: rvalue references extend the lifespan of the temporary object to which they are assigned. Non-const rvalue references allow you to modify the rvalue.

Can a function return an rvalue?

Typically rvalues are temporary objects that exist on the stack as the result of a function call or other operation. Returning a value from a function will turn that value into an rvalue. Once you call return on an object, the name of the object does not exist anymore (it goes out of scope), so it becomes an rvalue.


1 Answers

why can I assign a value to a rvalue ref like : int&& x = 10

That's not an assignment. That's initialisation. Here, a temporary object is materialised from the integer constant and the reference is bound to that temporary. Same thing can be done with lvalue references to const: const int& x = 10. It cannot be done with lvalue references to non-const since they cannot be bound to rvalues.

doesn't that mean that an rvalue ref is an lvalue

Only expressions have values. int&& x = 10; is a declaration and not an expression. Thus the declaration doesn't have a value in the first place.

The declaration contains an expression 10 which is a prvalue.

Types are not expressions either, so "rvalue reference is an lvalue" is meaningless.

Variables don't have value categories either. However id-expressions - which are just expressions that name a variable - do have a value category. They are lvalues regardless of the type of the named variable - yes, even if the type is rvalue reference.

like image 69
eerorika Avatar answered Sep 30 '22 17:09

eerorika