How to write destructor for union-like class

前端 未结 2 1163
一生所求
一生所求 2020-12-19 07:04

I\'m trying to use an union (C++) that has some non-primitive variables, but I\'m stuck trying to create the destructor for that class. As I have read, it is not possible to

2条回答
  •  庸人自扰
    2020-12-19 07:51

    This grouping (union + enum value for discriminating type) is called a discriminated union.

    It will be up to you to call any construction/destruction, because the union itself cannot (if it could, it would also be able to discriminate for initialized/non-initialized types within the union, and you would not need the enum).

    Code:

    class LuaVariant // no public access to the raw union
    {
    public:
        LuaVariant() : type(VARIANT_NONE) { }
        ~LuaVariant() { destroy_value(); }
    
        void text(std::string value) // here's a setter example
        {
            using std::string;
            destroy_value();
            type = VARIANT_TEXT;
            new (&value.text) string{ std::move(value) };
        }
    private:
    
        void destroy_value()
        {
            using std::string;
            switch(type)
            {
            case VARIANT_TEXT:
                (&value.text)->string::~string(); 
                break;
            case VARIANT_POSITION:
                (&value.pos)->Position::~Position(); 
                break;
            case VARIANT_NUMBER:
                value.number = 0;
                break;
            default:
                break;
            }
        }
    
        LuaVariantType_t type;
        union {
            std::string text;
            Position pos;
            uint32_t number;
        } value;
    };
    

提交回复
热议问题