Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't rvalues have an address?

Why don't rvalues have a memory address? Are they not loaded into the RAM when the program executes or does it refer to the values stored in processor registers?

like image 834
user746341 Avatar asked Sep 10 '11 06:09

user746341


2 Answers

Your question ("Why don't rvalues have a memory address?") is a bit confused. An rvalue is a kind of expression. Expressions don't have addresses: objects have addresses. It would be more correct to ask "why can one not apply the address-of operator to an rvalue expression?"

The answer to that is rather simple: you can only take the address of an object and not all rvalue expressions refer to objects (for example, the expression 42 has a value but does not refer to an object).

Some rvalue expressions do refer to objects, but such objects lack persistence. An object referred to by an rvalue expression is a temporary object and is destroyed at the end of the expression in which it is created. Such objects do indeed have addresses (you can easily discover this by calling a member function on a temporary object; the this pointer must point to the temporary object and thus the temporary object must have an address).

This is the fundamental difference between lvalue expressions and rvalue expressions. Lvalue expressions refer to objects that have persistence: the object to which an lvalue expression refers persists beyond a single expression.

like image 79
James McNellis Avatar answered Sep 25 '22 11:09

James McNellis


Think of rvalue as value of an expression. The value itself doesn't have address. But the objects involve in the expression do have address. You can take address of an object, even be it a temporary object.

Consider this,

const int & i = 10; //ok

Here, 10 is an rvalue, so it appears that &i is an address of the 10. No, that is wrong. &i is an address of the temporary object of type int, which is created out of the expression 10. And since the temporary object cannot be bound to non-const reference, I use const. That means, the following is an error:

int & i = 10; //error
like image 20
Nawaz Avatar answered Sep 25 '22 11:09

Nawaz