Questions Regarding C++ Non-Pod Unions

Questions regarding C++ non-POD unions

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.

Can a structure with union members be qualified as POD?

Yes - even union types merely contains data, and no methods, constructors, etc.

See:

What are POD types in C++?

Update
Provided, of course, the union only contains POD types.

See:

Questions regarding C++ non-POD unions

What are POD types in C++?

POD stands for Plain Old Data - that is, a class (whether defined with the keyword struct or the keyword class) without constructors, destructors and virtual members functions. Wikipedia's article on POD goes into a bit more detail and defines it as:

A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type.

Greater detail can be found in this answer for C++98/03. C++11 changed the rules surrounding POD, relaxing them greatly, thus necessitating a follow-up answer here.

Is there any difference between structure and union if we have only one member?

In C: None. The famous "space-saving joke" #define struct union is almost not a joke.

In C++98: Unions can only have POD members, non-union classes can have arbitrary members.

In C++11: Unions can have arbitrary data members of object type (but not of reference type), but their use is more restricted that that of non-union classes. (Namely: a union cannot have virtual member functions, cannot be a base class and cannot have base classes.) Also, you have to write more code to make a one-member union work as opposed to a one-member non-union class, since you have to write constructors and the destructor yourself.



Related Topics



Leave a reply



Submit