访问工会中相同类型的非活动成员 [英] Accessing same-type inactive member in unions

查看:73
本文介绍了访问工会中相同类型的非活动成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的东西:

union DataXYZ
{
    struct complex_t
    {
        float real, imag;
    } complex;

    struct vector_t
    {
        float magnitude, phase;
    } vector;
};

我有一些向量,它们是通用工作区内存,在此之后我会相应地使用这些字段语义上下文。

I have some vectors of these, being general-purpose workspace memory, where I use the fields accordingly after the semantic context.

我知道当最后一个活动成员是另一个字段(并键入?)时,读取联合中的字段是未定义的行为。当类型和布局完全匹配时,这有关系吗?

I know it's undefined behaviour to read a field in a union, when the last active member was another field (and type?). Does this matter when the types and layout match exactly?

我一直在评论其他类似的问题,要求提供能保证其性能的参考,但仍未解决-因此就是这个问题。

I've been commenting on some other similar questions, asking for references that guarantee the behaviour, but nothing came up yet - hence this question.

推荐答案

,您可以阅读此特殊信息中的其他成员情况

这是C ++ 11/14标准必须说的:

This is what the C++11/14 standard has to say:


9.5-联盟

在一个联合中,最多可以有一个非静态数据成员处于活动状态
可以随时存储,也就是说,最多可以随时将一个非静态数据
成员的值存储在联合中。

In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time.

但是在本节之后立即出现的注释使您的特定实例合法,因为为简化工会的使用而做了一项特殊保证

But the note immediately after the section makes your particular instance legal since one special guarantee is made in order to simplify the use of unions:


[注意:如果标准版式工会ains共享共同的初始序列(9.2)的几个标准布局
结构,并且如果此标准布局联合类型的对象
包含标准布局
结构之一,则为允许检查任何
标准布局结构成员的公共初始序列;参见9.2。 — 尾注]

[ Note: 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 ]

和您的结构 s 要共享一个常见的初始序列:

And your structs do share a common initial sequence:


9.2.16-班级成员

两种标准布局
结构(第9条)的常见初始序列是非静态数据
成员和位的最长序列-字段以声明顺序排列,从每个struct中的第一个
这样的实体开始,这样相应的实体
具有布局兼容类型,并且这两个实体都不是位字段
或两者都是具有相同宽度的位域。

The common initial sequence of two standard-layout struct (Clause 9) types is the longest sequence of non- static data members and bit-fields in declaration order, starting with the first such entity in each of the structs, such that corresponding entities have layout-compatible types and either neither entity is a bit-field or both are bit-fields with the same width.

这篇关于访问工会中相同类型的非活动成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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