访问位域联合是 C++ 标准中常见的初始数据未定义行为
Is accessing bitfield unions common initial data undefined behavior in C++ standards
类似于 c union and bitfields 但在 C++
中并且包括对初始序列的访问
类似于Union common initial sequence with primitive但使用bitfields
我想做的是:
struct A
{
short common : 1;
short a1: 5;
short a2: 8;
};
struct B
{
short common : 1;
short b1: 3;
short b2: 4;
short b3: 6;
};
union C
{
A a;
B b;
};
然后使用如下:
short foo(C data)
{
if (data.a.common)
{
return data.a.a1*data.a.a2;
}
return data.b.b1*data.b.b2*data.b.b3;
}
问题似乎是,如果 data.a.common
为假,代码将通过 A
的成员访问作为 B
的数据集
标准中似乎有关于并集和类似初始序列的语言,但不确定 common
因为 bitfield
会算
9.5.1 it is permitted to inspect the common initial sequence of any of standard-layout struct members;
任何澄清将不胜感激
来自 the definition of common initial sequence:
The common initial sequence of two standard-layout struct ([class.prop]) 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, either both entities are declared with the no_unique_address attribute ([dcl.attr.nouniqueaddr]) or neither is, and either both entities are bit-fields with the same width or neither is a bit-field.
struct A
和 struct B
的公共初始序列由第一个位字段 common
.
组成
类似于 c union and bitfields 但在 C++
中并且包括对初始序列的访问
类似于Union common initial sequence with primitive但使用bitfields
我想做的是:
struct A
{
short common : 1;
short a1: 5;
short a2: 8;
};
struct B
{
short common : 1;
short b1: 3;
short b2: 4;
short b3: 6;
};
union C
{
A a;
B b;
};
然后使用如下:
short foo(C data)
{
if (data.a.common)
{
return data.a.a1*data.a.a2;
}
return data.b.b1*data.b.b2*data.b.b3;
}
问题似乎是,如果 data.a.common
为假,代码将通过 A
B
的数据集
标准中似乎有关于并集和类似初始序列的语言,但不确定 common
因为 bitfield
会算
9.5.1 it is permitted to inspect the common initial sequence of any of standard-layout struct members;
任何澄清将不胜感激
来自 the definition of common initial sequence:
The common initial sequence of two standard-layout struct ([class.prop]) 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, either both entities are declared with the no_unique_address attribute ([dcl.attr.nouniqueaddr]) or neither is, and either both entities are bit-fields with the same width or neither is a bit-field.
struct A
和 struct B
的公共初始序列由第一个位字段 common
.