Where in the C++ Standard is the memory layout of objects documented?

1.7k Views Asked by At

This is a big question, so I'm asking for a reference rather than a booklet-sized answer. I'm going through Stroustrup's Tour of C++, and it seems like the way objects are laid out is memory is fundamental to the design of many C++ features, e.g. PODs vs aggregates vs classes with virtual members.

Unfortunately, the Tour itself doesn't cover this subject in detail, and skimming the ToCs of some standard references such as C++ Primer 5ed and TCPPPL 4ed doesn't show whether or where they cover it.

1

There are 1 best solutions below

4
On BEST ANSWER

[class.mem]/18:

Non-static data members of a (non-union) class with the same access control 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 and virtual base classes.

and [class.mem]/25:

If a standard-layout class object has any non-static data members, its address is the same as the address of its first non-static data member. Otherwise, its address is the same as the address of its first base class subobject (if any). [ Note: There might therefore be unnamed padding within a standard-layout struct object, but not at its beginning, as necessary to achieve appropriate alignment. — end note ] [ Note: The object and its first subobject are pointer-interconvertible ([basic.compound], [expr.static.cast]). — end note ]

There is also [dcl.array] which indicates that arrays are contiguous in memory, [class.bit] which talks about bit-fields, and [intro.object] which talkes about object size and the concept of overlapping subobjects.

There may be other places. There's no one spot.