Question

In the last few days I've been trying to grasp an apparently trivial principle behind lvalue/rvalue references. Let us define a new rvalue reference:

int&& x = 12;

x is therefore an lvalue expression of type int&&. Since x is a lvalue, it can be bound to a lvalue reference of the same type, i.e., a lvalue reference of type int&&. Such a lvalue reference would be defined as:

int&& & ref_x = x; // non-working code, just for the sake of explanation

Of course, it is not possible to explicitly define a reference to a reference, and the correct way to perform the binding is as follows:

int& ref_x = x;

C++ Primer reports the following about using references as initializers:

when we use a reference as an initializer, we are really using the object to which the reference is bound

On the other hand, the lvalue reference must match the type of the lvalue expression. What am I missing? Is reference collapsing involved in this case?

Thanks.

Was it helpful?

Solution

No, x (as an expression) is an expression of type int. The type of the value of an expression is never a reference. In fact, x is also an lvalue, since it is a named thing.

Also, there are no references to references, for the same reason: References bind to values, and values are never references.

If you're ever confused, just keep telling yourself: The value of an expression is always an object type. Whether the value category of an expression is l or r only determines what sort of things the value can bind to; it has no effect on its type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top