C++11 gave us to possibility to use non-POD types within unions, say I have the following piece of code;
union
{
T one;
V two;
} uny;
Somewhere within my class, only one member will be active at a time, now my questions are rather simple.
- What is the default value of uny? - undefined?
- Whenever my class is destructed, which members (within the union), if any will be destructed?
- Suppose I have to std::typeinfo to keep track of which is the active member, should I then call the destructor explicitly on that member in the destructor?
- Does anyone have a link to the language proposal, which changed unions to accept non-POD 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.
Alternatives to union:
std::any
/ std::variant
(C++17)
boost::any
/ boost::variant
These allow to use non-POD data types.
来源:https://stackoverflow.com/questions/19764150/questions-regarding-c-non-pod-unions