c++language-lawyer

Union's default constructor is implicitly deleted


The following code:

struct non_trivially {
    non_trivially() {};
};

union U {
    bool dummy{false};
    non_trivially value;
};

int main() {
    U tmp;
}

https://godbolt.org/z/1cMsqq9ee

Produces next compiler error on clang (13.0.0):

source>:11:7: error: call to implicitly-deleted default constructor of 'U'
    U tmp;
      ^ <source>:7:19: note: default constructor of 'U' is implicitly deleted because variant field 'value' has a non-trivial default constructor
    non_trivially value;

But successfully compiles using MSVC (19.30).

According to the cppreference it should be a valid code: https://en.cppreference.com/w/cpp/language/union

If a union contains a non-static data member with a non-trivial default constructor, the default constructor of the union is deleted by default unless a variant member of the union has a default member initializer .

In my example there is an alternative in U with a default member initializer so default constructor shouldn't be deleted, but it is. What am I missing?


Solution

  • Finally it was fixed in clang-17: https://godbolt.org/z/97rqexTxE