我正在使用一个 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/