Compile Time Error: Union default constructor is deleted

Compile Time Error: Union default constructor is deleted

以下 C++ 代码无法编译。据我调查这个问题,我知道问题是因为联合的默认构造函数已被编译器删除。在线说明如下:

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.

struct A {
   int val;
   A() : val(0) {}
};

union B
{
   A a;
};

B b;

为什么 struct A 的默认构造函数被认为是非平凡的?我该如何解决这个问题才能使这段代码成功编译?

Why is the default constructor of struct A considered non-trivial?

因为是用户声明的。

具有简单构造函数的 类 示例:

struct Trivial {
    int val;
};

struct Trivial2 {
    int val;
    Trivial2() = default;
};

作为奖励,这很重要:

struct NonTrivial {
    int val;
    NonTrivial();
};
NonTrivial::NonTrivial = default;

但是,如果您希望 A::val 被零初始化,您需要向联合体添加一个默认成员初始化程序:

union B {
   A a = {};
};