I get compiler error by Clang 3.8 and GCC 5.3 if I want to declare my default
-ed default constructors as constexpr
. According to this stackoverflow question it just should work fine:
struct A
{
constexpr A() = default;
int x;
};
however:
Error: defaulted definition of default constructor is not constexpr
Have you got any clue what is actually going on?
For types with trivial default constructors, default initialization does not compile in constexpr.
A constructor that is declared with a constexpr specifier is a constexpr constructor. Previously, only expressions of built-in types could be valid constant expressions. With constexpr constructors, objects of user-defined types can be included in valid constant expressions.
It is difficult to say this is an absolute, but generally, yes, the default constructor should be noexcept. There could be an exception if, for example, members of the class have default constructors (or otherwise are initialized appropriate as members) where they could throw an exception.
The compiler-defined default constructor is required to do certain initialization of class internals. It will not touch the data members or plain old data types (aggregates like an array, structures, etc…). However, the compiler generates code for the default constructor based on the situation.
As it stands, x remains uninitialized, so the object can not be constructed at compile time.
You need to initialize x:
struct A
{
constexpr A() = default;
int x = 1;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With