简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM