Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind non-const lvalue reference to rvalue

Tags:

c++

#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?

like image 553
Rich Avatar asked Oct 18 '22 12:10

Rich


1 Answers

[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.

like image 124
Anton Savin Avatar answered Nov 11 '22 20:11

Anton Savin