为什么 C++ 标准特别为具有不同访问说明符的 class 数据成员的内存布局提供了余地?
Why does the C++ standard specifically grant leeway regarding memory layout of class data members with different access specifiers?
C++11 标准要求对 class 的非静态数据成员在内存中进行排序,但随后专门为具有不同访问说明符的成员开辟了一个豁免。
为什么?
§ 9.2.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 (Clause 11). 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).
标准的这一部分以前在 Whosebug 上出现过,但我认为从来没有人解释过。
N2062 is the first C++ paper that deals with changes to C++98/03's POD definition. It was written as a means to resolve core issue 568,这是关于 PODs 和类型布局。它代表了导致 C++11 的标准布局和琐碎的可复制性定义的设计的开始。
然而,N2062 甚至从未考虑定义具有不同访问控制的成员的布局。它甚至没有说明为什么要实施此限制。 the final version of that proposal 也没有,它实际上给了我们简单可复制和标准布局的定义。这些提案的所有版本都将访问控制限制视为既成事实,而不是本来可以改变的事情。
所有这些都表明提案的作者至少知道 compiler/ABI 可以根据访问控制更改成员的顺序。
C++11 标准要求对 class 的非静态数据成员在内存中进行排序,但随后专门为具有不同访问说明符的成员开辟了一个豁免。
为什么?
§ 9.2.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 (Clause 11). 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).
标准的这一部分以前在 Whosebug 上出现过,但我认为从来没有人解释过。
N2062 is the first C++ paper that deals with changes to C++98/03's POD definition. It was written as a means to resolve core issue 568,这是关于 PODs 和类型布局。它代表了导致 C++11 的标准布局和琐碎的可复制性定义的设计的开始。
然而,N2062 甚至从未考虑定义具有不同访问控制的成员的布局。它甚至没有说明为什么要实施此限制。 the final version of that proposal 也没有,它实际上给了我们简单可复制和标准布局的定义。这些提案的所有版本都将访问控制限制视为既成事实,而不是本来可以改变的事情。
所有这些都表明提案的作者至少知道 compiler/ABI 可以根据访问控制更改成员的顺序。