4

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?

Fedor
  • 13,764
  • 2
  • 28
  • 94
  • 6
    Does this answer your question? [how to initialize a constexpr reference](https://stackoverflow.com/questions/28614591/how-to-initialize-a-constexpr-reference) – dewaffled Oct 08 '21 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*: https://timsong-cpp.github.io/cppwp/n4861/expr.const#11.2 Is it applicable to references as well? – Fedor Oct 08 '21 at 19:30

0 Answers0