我正在编写一个类,它通过 union 存储多种数据类型之一(在本例中为 QBrush
和 int
)并通过使用 记住哪个是事件的>键入
成员。
class X
{
public:
X(const QBrush &brush)
: type(0), b(brush) { }
X(int integer)
: type(1), i(integer) { }
X(const X &other)
: type(other.type)
{
if (type == 0)
b = other.b;
else i = other.i;
}
~X() { }
private:
int type;
union
{
QBrush b;
int i;
};
};
int main(int argc, char *argv[])
{
X x = X(QBrush(Qt::red));
X y = X(x);
return 0;
}
我很惊讶这个程序崩溃了。目前我没有调试器,所以我只知道它在分配画笔时在 X
的复制构造函数中崩溃。请注意,当我将复制构造函数代码替换为
X(const X &other)
: type(other.type), b(other.b), i(other.i)
{ }
这让我更加困惑。
QBrush
是 Qt 提供的一些类。我想崩溃与此类的内部结构有关。但我不知道。有人知道发生了什么事吗?
最佳答案
这是一个错误:
X(const X &other)
: type(other.type)
{
if (type == 0)
b = other.b; // b is not constructed yet
else i = other.i;
}
b
尚未构建,但您对其调用了 operator=
。
使用 new(&b) QBrush(other.b)
,它使用复制构造函数正确构造了 b
。
关于c++ - 为什么在复制构造函数中分配 union 成员会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47165416/