Questions regarding C++ non-POD unions

久未见 提交于 2019-11-28 11:01:18

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!