数组元素算作共同的初始序列吗? [英] Do array elements count as a common initial sequence?

查看:75
本文介绍了数组元素算作共同的初始序列吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相关的排序:

数组元素是否算作共同的初始序列?

Do elements of arrays count as a common initial sequence?

struct arr4 { int arr[4]; };
struct arr2 { int arr[2]; };

union U
{
    arr4 _arr4;
    arr2 _arr2;
};

U u;
u._arr4.arr[0] = 0; //write to active
u._arr2.arr[0]; //read from inactive

根据此cppreference页面:

在具有非工会类类型T1的活动成员的标准版式联合中,允许读取另一个非工会类类型T2的联合成员的非静态数据成员m,前提是m是T的一部分. T1和T2的共同初始序列....

In a standard-layout union with an active member of non-union class type T1, it is permitted to read a non-static data member m of another union member of non-union class type T2 provided m is part of the common initial sequence of T1 and T2....

这是合法的,还是非法的整形?

Would this be legal, or would it also be illegal type punning?

推荐答案

C ++ 11说(9.2):

C++11 says (9.2):

如果标准布局联合包含两个或多个共享共同初始序列的标准布局结构, 并且如果标准布局联合对象当前包含这些标准布局结构之一,则允许 检查其中任何一个的公共初始部分. 两个标准布局结构共享一个共同的首字母 如果相应的成员具有与布局兼容的类型,则该序列,并且两个成员都不是位字段或 对于一个或多个初始成员的序列,两者都是具有相同宽度的位域.

If a standard-layout union contains two or more standard-layout structs that share a common initial sequence, and if the standard-layout union object currently contains one of these standard-layout structs, it is permitted to inspect the common initial part of any of them. Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.

关于大小不同的数组是否形成有效的公共初始序列,3.9说:

As to whether arrays of different size form a valid common initial sequence, 3.9 says:

如果两个T1和T2是同一类型,则T1和T2是布局兼容类型

If two types T1 and T2 are the same type, then T1 and T2 are layout-compatible types

这些数组不是同一类型,因此不适用.数组没有特别的例外,因此数组可能与布局不兼容,并且不会形成共同的初始序列.

These arrays are not the same type, so this doesn't apply. There is no special further exception for arrays, so the arrays may not be layout-compatible and do not form a common initial sequence.

不过,实际上,我知道一个编译器(GCC):

In practice, though, I know of a compiler (GCC) which:

  • 忽略通用初始序列"规则,并且
  • 无论如何都允许类型化修剪,但仅当访问是通过联合类型"(如您的示例)时,才间接遵守公共初始序列"规则(因为公共初始序列"表示通用)编译器支持的体系结构上的初始布局.)

我怀疑许多其他编译器都采用了类似的方法.在您的示例中,当您通过并集对象键入双关语时,此类编译器将为您提供预期的结果-从非活动成员读取内容将为您提供通过非活动成员写入的值.

I suspect many other compilers take a similar approach. In your example, where you type-pun via the union object, such compilers will give you the expected result - reading from the inactive member should give you value written via the inactive member.

这篇关于数组元素算作共同的初始序列吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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