例如,
class A { private: int a1; int a2:3; public: int z; int a3:2; int a4:5; private: int a5:2; }
是a1,a2和a5俱乐部搭配在一起用于内存分配,还是简单的a1,a2,a3,a4,a5?
如果发生碰撞,在位字段的情况下,它可能会改变类的大小.
解决方法
>在C11中,这样做得到了加强,使得具有相同可访问性的成员必须按宣布的顺序进行. (例如,在您的示例中禁用a5 a1 a2 f a3 a4,因为在示例中的a1和a2之后声明a5)未指定具有不同可访问性的成员之间的顺序.
>编译器可以在任何成员之间插入填充(例如为了保持对齐)
位字段的表示是未指定的.它们可以以任何顺序排列,并且不遵守任何先前的规则.因为你不能拿一个位字段的地址,没有机制来观察这个.
具体标准参考(强调我的):
C 03 9.2 [class.mem] / 12:
Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).
N3376(第一篇文章C11草案)9.2 [class.mem] / 13:
Nonstatic data members of a (non-union) class with the same access control (Clause 11) are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified. Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).
N3376 9.6 [class.bit] / 1:
[…] Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. […]
/ 3:
[…] The address-of operator & shall not be applied to a bit-field,so there are no pointers to bitfields. […]