Why is the uninitialized constexpr variable not constant?

I am not sure if this is a compiler error, or if I misunderstand constexpr:

struct S{}; constexpr S s1{}; constexpr S s2; struct test{ static constexpr auto t1 = s1; static constexpr auto t2 = s2; //error here }; 

GCC 4.8 gives me an error with an odd error: the field initializer is not a constant. "Is s2 not constant? If so, why?

For clarity, I actually use a bunch of empty structures in my code (for the metaprograms https://github.com/porkybrain/Kvasir ), so I'm really interested in this specific example.

+6
source share
1 answer

Update: The code must compile because [class.ctor]/5 reads:

An implicit default constructor executes a set of class initializations that will be executed by a user-written default constructor for this class without the ctor initializer (12.6.2) and an empty compound instruction. If this custom default constructor satisfies the requirements of the constexpr constructor (7.1.5), the implicitly defined default constructor is constexpr .

And since S is just an empty structure, the implicitly defined constructor is empty by default and thus satisfies the requirements of constexpr .

So, here you are dealing with the imperfection of compilers that you need to work around somehow.


Old answer:

Clang emits a more reasonable error message:

 main.cpp:3:13: error: default initialization of an object of const type 'const S' requires a user-provided default constructor constexpr S s2; ^ 

[dcl.constexpr] / 9 gives an explanation and even almost exactly your example code:

A constexpr qualifier used in declaring an object declares the object as const. Such an object must be of a literal type and must be initialized. (...) [Example:

 struct pixel { int x, y; }; constexpr pixel ur = { 1294, 1024 };// OK constexpr pixel origin; // error: initializer missing 

-end example]

+4
source

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


All Articles