Search code examples
c++pointersconstantsliteralslvalue

c++ is const pointer to literal valid?


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?


Solution

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