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

风格不统一 提交于 2019-12-23 12:54:40

问题


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:


[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.



来源:https://stackoverflow.com/questions/50803202/where-in-the-c-standard-is-the-memory-layout-of-objects-documented

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