Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constexpr defaulted default constructors

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?

like image 898
plasmacel Avatar asked Apr 03 '16 23:04

plasmacel


People also ask

Are default constructors constexpr?

For types with trivial default constructors, default initialization does not compile in constexpr.

Can constructors be 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.

Are default constructors Noexcept?

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.

Is default constructor mandatory in C++?

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.


1 Answers

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;
};
like image 85
Jorn Vernee Avatar answered Oct 04 '22 03:10

Jorn Vernee