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?

Fedor
  • 17,146
  • 13
  • 40
  • 131
  • 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
  • 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](https://learn.microsoft.com/en-us/cpp/cpp/constexpr-cpp?view=msvc-170) – Nimrod Jun 17 '22 at 03:30

0 Answers0