Question

I have read that the code below is valid in C++11:

int && a = 3;
a = 4;

Is it supposed to write 4 in the memory address where the numeric literal 3 is stored? Maybe some compiler optimizations would prevent this from happening, but is it supposed to do so?

Was it helpful?

Solution

When you assign a prvalue that is not of class type to an rvalue reference, a temporary object is created and the reference is bound to that. You are simply modifying the temporary object.

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:

  • If the reference is an lvalue reference [...]

  • Otherwise, [...] or the reference shall be an rvalue reference.

    • If the initializer expression

      • is an xvalue (but not a bit-field), class prvalue, array prvalue or function lvalue [...], or

      • has a class type [...]

      [...]

    • Otherwise, a temporary of type “cv1 T1” is created and initialized from the initializer expression using the rules for a non-reference copy-initialization (8.5). The reference is then bound to the temporary.

Conceptually, a prvalue is just a value that may or may not have come from some object in memory. Literals don't have a corresponding object in memory, so this rule forces an object to be created.

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