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