I know lvalues can be converted into const reference. I'm curious if I can get a pointer to those lvalues.
If I write
const int* p = &3; //ERROR: lvalue required as unary operand '&'
I get this error. However,
const int* p = &((const int&)3);
this compiles. In this case, is the result of *p guaranteed to be 3?
This constructs a temporary int(3)
and binds it to a const reference. p
is made to point to that temporary. The lifetime of the temporary is extended to match that of the reference - but the reference itself is a temporary and is destroyed at the semicolon, leaving p
a dangling pointer. Any attempt to use p
afterwards (other than assigning a new value to it) would exhibit undefined behavior.
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