C++ - 与非平凡 class 成员类型联合?

C++ - union with nontrivial class member type?

我正在使用一个联合,该联合有一个 class 成员,它使用菱形继承,但程序在分配给该成员时遇到分段错误。

我的怀疑是我需要添加一些复制构造函数,但经过多次尝试,正确的做法仍然让我望而却步。

我在这里包含了一个最小的、可重现的例子。

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();

在分配之前,分段错误消失了。虽然,我不推荐这个技巧。


正如评论中已经提到的,如果您有可用的 C++17,std::variant 会更合适。该示例将变为

std::variant<Final, int> example{ Final() };
example = -1;
example = Final();

从 c++11 开始,联合定义自己的构造函数的成员 and/or copy-control 成员是允许的,但是当联合有 built-in 类型的成员时,我们可以使用普通赋值来 更改联合持有的价值,但不适用于拥有以下成员的联合 重要的 class 类型。当我们将 union 的值与 class 类型,我们必须构造或销毁该成员。例如看下面的代码

#include <iostream>
#include <new> // for placement new

class Type   // non built in type with constructors
{
private:
    int val;

public:
    Type() : val{0} {    }

    explicit Type(int v) : val{v}  {  }

    Type(const Type &obj) : val{obj.val} {  }

    int getval()  {   return val;  }
};

class unionexample   // I enclose union with class for readability
{
private:
    enum { INT,TYPE } OBJ;

    union
    {
        Type Tval;  // non build in type
        int ival;   // build in type
    };

public:
    unionexample() : ival{0}, OBJ{INT} // default with int
    { }

    unionexample(const unionexample &obj) : OBJ{obj.OBJ}
    {
        switch (obj.OBJ)
        {
        case INT:
            this->ival = obj.ival;
            break;
        case TYPE:
            new (&this->Tval) Type(obj.Tval);
            break;
        }
    }

    unionexample &operator=(int v)
    {
        if (OBJ == TYPE)
        {
            Tval.~Type(); // if it is TYPE destruct it
        }

        ival = v; // assign

        OBJ = INT;

        return *this;
    }

    unionexample &operator=(Type v)
    {
        if (OBJ == TYPE)
        {
            Tval = v;  // if it is alderdy Type just assign
        }

        new (&Tval) Type(v); // else construct

        OBJ = TYPE;

        return *this;
    }

    void print()
    {
        switch (OBJ)
        {
        case INT:
            std::cout << "ival = " << ival << std::endl;
            break;

        case TYPE:
            std::cout << "Tval = " << Tval.getval() << std::endl;
            break;
        }
    }

    ~unionexample()
    {
        if (OBJ == TYPE)  // if it is TYPE we must destruct it
            Tval.~Type();
    }
};

int main()
{
    unionexample ue;
    ue.print();
    ue = Type(1);
    ue.print();
}

输出:

ival = 0
Tval = 1

Run Here

你的情况

int main()
{
    Example example{ value : Final() };     // construct with Final

    example.value.~Final();                 // destruct Final

    example.i = -1;                         // assign int built in type
    
    new(&example.value)  Final();           // construct
    
    example.value.~Final();                 // destruct finally
}

如果您问的这个问题不是学习目的,您可以使用 std::variant 作为其他答案。

谢谢。