Constexpr reference to a non-constant object

Is it allowed to declare a non-constant link as constexpr? Code example:

int x = 1;
constexpr int& r = x;

This is accepted by gcc and clang (I tried several current and past versions of both, back in C ++ 11, and all this was accepted). However, I think this should not be accepted because C ++ 14 [dcl.constexpr / 9] says:

if the constexpr specifier is used in the link declaration, the expression that appears in its initializer must be a constant expression

and is xnot a constant expression.

The language in the latest C ++ 17 project [dcl.constexpr] has changed and does not even mention more links constexpr, I can’t understand what it is trying to say about them.

+4
source share
1 answer

Assuming it xhas a static storage duration, the lvalue expression xis a perfectly valid constant expression.

If you are using xin a context requiring prvalue, which leads to the use of the lvalue-to-rvalue transform, then the resulting prvalue expression - invoking it TO_RVALUE(x)- will not be a constant expression, for obvious reasons. But in the case of link binding, there is no such conversion.

+4
source

Source: https://habr.com/ru/post/1675318/


All Articles