关于C ++非POD联合的问题 [英] Questions regarding C++ non-POD unions

查看:134
本文介绍了关于C ++非POD联合的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11让我们可以在工会内使用非POD类型,例如我有以下代码:

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. uny的默认值是多少? - undefined?

  2. 每当我的类被破坏,哪些成员(在联合内),如果有的话会被破坏?

    • 假设我必须使用std :: typeinfo来跟踪哪个是活动成员,那么我应该在析构函数中明确地调用析构函数吗?


推荐答案

你大部分都是自己的。标准中的注释解释了这一点(9.5 / 2):

You're mostly on your own. A note in the standard explains this (9.5/2):


如果联合的任何非静态数据成员具有非平凡默认
构造函数(12.1),拷贝构造函数(12.8),移动构造函数(12.8),拷贝赋值运算符(12.8),移动
赋值运算符(12.8)或析构函数的联合必须是用户提供的
,否则它将被隐式删除(8.4.3)为联合。

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.

因此,如果任何成员构造函数是不重要的,你需要为union创建一个构造函数(如果它们都是微不足道的,默认状态将是未初始化的,如 union {int; double;} )。如果任何成员有一个析构函数,你需要为联合体写一个析构函数,必须注意找出活动元素。

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.

还有一个注意事项(9.5 / 4 )关于非约束联合的典型用法:

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.

这篇关于关于C ++非POD联合的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆