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

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.