Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 540
eivour Avatar asked Jan 30 '23 17:01

eivour


1 Answers

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.

like image 109
Igor Tandetnik Avatar answered Feb 08 '23 17:02

Igor Tandetnik