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.
A POD (plain old data) object has one of these data types--a fundamental type, pointer, union, struct, array, or class--with no constructor. Conversely, a non-POD object is one for which a constructor exists.
Unrestricted union (C++11) That means you can't use a union as a base class, or inherit from another class, or have virtual functions.
In computer science and object-oriented programming, a passive data structure (PDS, also termed a plain old data structure, or plain old data, POD) is a term for a record, to contrast with objects.
A Plain Old Data (POD) structure is an aggregate class that contains only PODs as members. It doesn't have any user-defined constructors or destructors. There are also no non-static members of the pointer-to-member type in it. A POD structure is a struct or class which only has member variables.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With