Questions regarding C++ non-POD unions
Alternatives to union:
std::any
/ std::variant
(C++17)
boost::any
/ boost::variant
These allow to use non-POD data types.
You're mostly on your own. A note in the standard explains this (9.5/2):
If any non-static data member of a union has a non-trivial default constructor (12.1), copy constructor (12.8), move constructor (12.8), copy assignment operator (12.8), move assignment operator (12.8), or destructor (12.4), the corresponding member function of the union must be user-provided or it will be implicitly deleted (8.4.3) for the union.
So if any of the member constructors are non-trivial, you need to write a constructor for the union (if they are all trivial, the default state will be uninitialized, like for union { int; double; }
). If any members have a destructor, you need to write a destructor for the union which must take care of figuring out the active element.
There's a further note (9.5/4) about typical usage of an unconstrained union:
In general, one must use explicit destructor calls and placement new operators to change the active member of a union.