#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 “cv2T2” as follows:
...
(5.2.2.2) — IfT1is a non-class type, a temporary of type “cv1T1” 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With