13

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?

Community
  • 1
  • 1
plasmacel
  • 8,183
  • 7
  • 53
  • 101

1 Answers1

19

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;
};
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93
  • Yeah I also figured it out in the meantime. That referenced SO question / answer is pretty incomplete and misleading. – plasmacel Apr 03 '16 at 23:21
  • 2
    @plasmacel the accepted answer covers the required info... in bold near the end it explains that if you do not write `constexpr` then the function is constexpr if and only if it meets the criteria for constexpr; and then the last paragraph explains that if you can write `constexpr` yourself if you want to get a compilation error when your function did not meet the criteria (as yours does not) – M.M Apr 03 '16 at 23:31