The snippet below was obtained from DR 2083 by Hubert Tong.
extern int globx;
int main() {
const int &x = globx;
struct A {
const int *foo() { return &x; }
} a;
return *a.foo();
}
Then the author writes:
x
satisfies the requirements for appearing in a constant expression, but applying the lvalue-to-rvalue converstion tox
does not yield a constant expression.
Why applying the lvalue-to-rvalue conversion to x
does not yield a constant-expression?
Applying the lvalue-to-rvalue conversion to x
reads the value of the mutable global variable globx
, which makes it not a constant expression as the value of globx
is subject to change (and, even if it were const
, there would be the issue of its value not being known at compile time). Of course, this is not surprising: no one would expect int{x}
to be a constant expression. The DR points out that this fact should, nonetheless, not cause the odr-use of x
and thus the code should be well-formed: since x
has constant initialization, the compiler can just translate &x
into &globx
.