c – 如何为类的私人和公共成员分配内存

一个课堂上,是私人会员分配在公共成员的单独内存中,还是按照定义的顺序分配所有成员?

例如,

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?

如果发生碰撞,在位字段的情况下,它可能会改变类的大小.

解决方法

>在给定的可访问性块中,成员的顺序被保留,但在C 03中未定义可访问性块成员顺序之间.这意味着在上面的示例中,a1,a5,z,a4将是有效的顺序.
>在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. […]

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...