【发布时间】:2020-09-24 09:58:09
【问题描述】:
我正在使用一个联合,它的成员是使用菱形继承的类,但程序在分配给该成员时遇到分段错误。
我的怀疑是我需要添加一些复制构造函数,但经过多次尝试后,我仍然无法正确执行此操作。
我在这里包含了一个最小的、可重现的示例。
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();
}
感谢任何知道如何做到这一点的人。
【问题讨论】:
-
这就是枚举的工作方式。
example.i = -1;将int i;标记为活动成员,访问其他成员是未定义的行为。不要尝试使用枚举进行类型双关语,它在 C++ 中不起作用,您得到的最好的结果是所谓的“通用初始序列”,但这当然不适用于虚拟。 -
@Quimby 你的意思是联合,而不是枚举,对吧?
-
C++ 联合使用起来真的很烦人,改用
std::variant。 -
@Quimby “仅在 C 中明确允许通过联合进行类型双关,而不是在 C++ 中” - 是的,但我没有看到 OP 试图在这里进行类型双关。 OP 不会写入一个成员,然后尝试从另一个成员读取。
-
@TedLyngmo 哇,显然我今天不会读也不会写,很抱歉。在这种情况下,请忽略我在此评论部分所说的一切:D
标签: c++ inheritance unions diamond-problem