5

If constexpr reference is initialized with just another constexpr object as in the example:

int main() { constexpr int a = 0; constexpr const int & b = a; } 

then both GCC and Clang reject it saying constexpr variable 'b' must be initialized by a constant expression, address of non-static constexpr variable 'a' may differ on each invocation of the enclosing function; add 'static' to give it a constant address.

At the same time MSVC accepts the example. Demo: https://gcc.godbolt.org/z/Whv7YeWKW

All compilers accept the code after adding static to a:

static constexpr int a = 0; 

Demo: https://gcc.godbolt.org/z/abeP4z64E

Is it really required by the standard that any constexpr reference be initialized only with a static object?

3
  • 6
    Does this answer your question? how to initialize a constexpr reference Commented Oct 8, 2021 at 12:19
  • Thanks. In C++20 standard I see the wording if the value is of pointer type, it contains the address of an object with static storage duration: timsong-cpp.github.io/cppwp/n4861/expr.const#11.2 Is it applicable to references as well? Commented Oct 8, 2021 at 19:30
  • It's definitely violating the standard. It must bind to an object with static lifetime. A reference may be declared as constexpr when both these conditions are met: The referenced object is initialized by a constant expression, and any implicit conversions invoked during initialization are also constant expressions. Quoted from MS doc Commented Jun 17, 2022 at 3:30

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.