c++ - 为什么在复制构造函数中分配 union 成员会崩溃?

标签 c++ constructor copy-constructor unions

我正在编写一个类,它通过 union 存储多种数据类型之一(在本例中为 QBrushint)并通过使用 记住哪个是事件的>键入成员。

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/

相关文章:

java - 如果父类(super class)没有默认构造函数,为什么此 Java 代码中的子类有默认构造函数?

c++ - 为什么复制和 move 构造函数以相同数量的 memcopies 结束?

c++ - 如何用按位运算实现位 vector ?

java - Java 中的构造函数和隐藏字段

c++ - 一个好的 C++ 原生多媒体库?

c++ - 使用 shared_ptr 进行条件构造?

c++ - 复制构造函数没有合适的默认构造函数

c++ 如何解决我的内存泄漏?

c++ - 如何使用boost在C++中获取带有尾随路径分隔符的路径

c++ - 函数指针失去值(value)