Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 649
Praxeolitic Avatar asked Dec 31 '16 10:12

Praxeolitic


1 Answers

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.

like image 88
Nicol Bolas Avatar answered Nov 10 '22 06:11

Nicol Bolas