How to write destructor for union-like class

前端 未结 2 1160
一生所求
一生所求 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:37

    If you want to use std::string in a union in C++11, you have to explicitly call its destructor, and placement new to construct it. Example from cppreference.com:

    #include 
    #include 
    #include 
    union S {
        std::string str;
        std::vector vec;
        ~S() {} // needs to know which member is active, only possible in union-like class 
    }; // the whole union occupies max(sizeof(string), sizeof(vector))
    
    int main()
    {
        S s = {"Hello, world"};
        // at this point, reading from s.vec is UB
        std::cout << "s.str = " << s.str << '\n';
        s.str.~basic_string();
        new (&s.vec) std::vector;
        // now, s.vec is the active member of the union
        s.vec.push_back(10);
        std::cout << s.vec.size() << '\n';
        s.vec.~vector();
    }
    

提交回复
热议问题