Why does the C++ standard specifically grant leeway regarding memory layout of class data members with different access specifiers?

[亡魂溺海] 提交于 2020-05-14 19:11:29

问题


The C++11 standard mandates an ordering in memory for the non-static data members of a class but then specifically carves out an exemption for members with different access specifiers.

Why though?

§ 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).

This part of the standard has come up on stackoverflow before but I don't think it has ever been explained.


回答1:


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, which is about PODs and type layouts. It represents the beginning of the design that leads to C++11's standard layout and trivial copyability definitions.

And yet, N2062 never even considers defining the layout of members with different access controls. It doesn't even give justification for why this restriction is in place. Nor does the final version of that proposal, which actually gives us trivially-copyable and standard-layout definitions. All versions of these proposals take the access control limitation as an fait accompli, rather than something that could have been changed.

All this suggests that the writer of the proposal had knowledge of at least one compiler/ABI that changes the order of members based on access controls.



来源:https://stackoverflow.com/questions/41407540/why-does-the-c-standard-specifically-grant-leeway-regarding-memory-layout-of-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!