放置std :: array< POD,N>是否安全?在工会里? [英] Is it safe to put an std::array<POD, N> in a union?

查看:75
本文介绍了放置std :: array< POD,N>是否安全?在工会里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样宣布的工会:

I have a union declared like that:

union
{
    int all[4];
    struct
    {
        int a, b, c, d;
    };
};

all 数组的点很简单

为了使其更简单,我想用 std :: array<代替它。 int,4> 。这会让我接触鼻恶魔吗?

To make it even simpler, I'd like to replace it with an std::array<int, 4>. Would that expose me to nasal demons?

推荐答案

首先,需要注意的是,在一个联合体中仅具有两个不同类型的对象永远不会被定义。未定义的是写一个,另一个读,一个例外:

First, it's important to note that merely having two objects of different types in a union is never undefined. What's undefined is to write to one and read from another, with one exception:


[C ++ 11: 9.5 / 1]: [注意:为了简化联合的使用,进行了一项特殊保证:如果标准布局联合包含多个共享的标准布局结构一个公共初始序列(9.2),并且如果此标准布局联合类型的对象包含一个标准布局结构,则可以检查任何标准布局结构成员的公共初始序列;参见9.2。 — 尾注] [..]

[C++11: 9.5/1]: [ Note: One special guarantee is made in order to simplify the use of unions: If a standard-layout union contains several standard-layout structs that share a common initial sequence (9.2), and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members; see 9.2. —end note ] [..]

现在,尽管没有在 std :: array 符合以下规则,因为它是仅包含元素成员的集合,这一事实似乎足以保证:

Now, although it's not written out specifically anywhere that std::array fits this rule, the fact that it's an aggregate with only element members seems enough of a guarantee:


[C ++ 11:23.3.2.1/2]:数组是一个聚合(8.5.1),可以使用以下语法初始化:

[C++11: 23.3.2.1/2]: An array is an aggregate (8.5.1) that can be initialized with the syntax:

  array< T,N> a = { 初始化列表 };

其中 initializer-list 是逗号分隔的列表,最多包含 N 个元素,其类型可转换为 T

where initializer-list is a comma-separated list of up to N elements whose types are convertible to T.

因此,不仅将工会放在首位是安全的,而且可以读写

So, it's safe not only to have the union exist in the first place, but also to read and write to either member at will.

因此,我的结论是:是;是安全的

这篇关于放置std :: array&lt; POD,N&gt;是否安全?在工会里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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