Rich
Rich

Reputation: 1851

Bind non-const lvalue reference to rvalue

#include <iostream>
using namespace std;

int main() {
    int &&rfint = 10;
    int &l = rfint;
    std::cout << l << std::endl;
    std::cout << ++l << std::endl;
    std::cout << &l << std::endl;
    return 0;
}

Using the above construct, I can directly manipulate the prvalue 10 through the non-const lvalue reference l. I can even take address of the prvalue. How does this work? Is it related to extended lifetime?

Upvotes: 5

Views: 233

Answers (1)

Anton Savin
Anton Savin

Reputation: 41301

[dcl.init.ref]/5:

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:
...
(5.2.2.2) — If T1 is a non-class type, a temporary of type “cv1 T1” is created and copy-initialized (8.5) from the initializer expression. The reference is then bound to the temporary.

So int &&rfint = 10; creates a temporary, and the reference is bound to it, not to 10 itself.

And yes, the lifetime of that temporary is extended to the lifetime of rfint, so you can do whatever you want with it while rfint is in scope.

Upvotes: 3

Related Questions