Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Questions regarding C++ non-POD unions

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.

  1. What is the default value of uny? - undefined?
  2. 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?
  3. Does anyone have a link to the language proposal, which changed unions to accept non-POD types?
like image 342
Skeen Avatar asked Nov 04 '13 08:11

Skeen


People also ask

What is non POD type?

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.

What is unrestricted union in C++?

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.

What is POD programming?

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.

What is plain old data C++?

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.


1 Answers

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.

like image 139
Kerrek SB Avatar answered Oct 24 '22 19:10

Kerrek SB