C++ - 与非平凡类成员类型的 union ?

标签 c++ inheritance unions diamond-problem

我正在使用一个 union ,它的成员是一个使用菱形继承的类,但是程序在分配给这个成员时遇到了段错误。
我的怀疑是我需要添加一些复制构造函数,但经过多次尝试,正确的方法仍然避开了我。
我在这里包含了一个最小的、可重复的示例。

struct Base
{
    Base() : a(0) {}
    Base(int x) : a(x) {}

    int a;
};

struct Derived1 : virtual public Base
{
    Derived1() {}
};

struct Derived2 : virtual public Base
{
    Derived2() {}
};

struct Final : public Derived1, public Derived2
{
    Final() {}
};

union Example
{
    Final value;
    int i;
};

int main()
{
    Example example{ Final() };
    example.i = -1;

    /* Segfault on the line below. 
     * If the above line

       example.i = -1;
     
     * is removed, the segfault is not encountered. */

    example.value = Final();
}
我感谢任何知道如何做到这一点的人。

最佳答案

由于Base类(class)是 virtual ,很可能有一些内部控制结构,当你分配

example.i = -1;
当你重新创建 value ,例如
new(&example.value) Final();
example.value = Final();
在分配之前,段错误消失了。虽然,我不会推荐这个黑客。

正如评论中已经提到的, std::variant 如果您有可用的 C++17,会更合适。然后该示例将变为
std::variant<Final, int> example{ Final() };
example = -1;
example = Final();

关于C++ - 与非平凡类成员类型的 union ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64044036/

相关文章:

c++ - 使用 GLAD 时无法命名变量 "far"和 "near"

c++ - 将抽象类(仅限纯虚函数)的继承/派生限制在某个类

c - 以下代码的输出.. union

c++ - 编译SDL2代码时出错

c++ - 改变线程任务?

python - 为什么 Python 类会继承对象?

c++ - 移植 C -> C++,在访问未命名 union 内的结构时遇到问题

c - 将结构与其中的结构 union 打包

c++ - 如何在外部类中调用内部类的函数?

c# - 可以禁止子类定义类吗?