繁体   English   中英

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

[英]C++ - union with nontrivial class member type?

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

我的怀疑是我需要添加一些复制构造函数,但是经过多次尝试,正确的方法仍然回避我。

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

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类是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 开始,允许具有定义自己的构造函数和/或复制控制成员的成员的联合,但是当联合具有内置类型的成员时,我们可以使用普通赋值来更改联合持有的值,但不适用于具有非平凡类类型成员的联合。 当我们在类类型的成员之间来回切换联合的值时,我们必须构造或销毁该成员。 例如见波纹管代码

#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

跑到这里

在你的情况下

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

谢谢。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM