How memory is allocated for private and public members of the class

后端 未结 2 1529
北恋
北恋 2020-12-31 10:47

In a class, are private members allocated in separate memory from public members, or all members allocated in the sequence of their definition?

For example,

2条回答
  •  感动是毒
    2020-12-31 11:32

    • Within a given accessibility block, the order of members is preserved, but between accessibility blocks member order is unspecified in C++03. This means that a1, a2, a5, z, a3, a4 would be a valid order in your example above.
    • In C++11 this is strengthened such that members with the same accessibility must be placed in declared order. (e.g. this bans a5 a1 a2 f a3 a4 in your example because a5 is declared after a1 and a2 in your example) Order between members with different accessibility is unspecified.
    • The compiler may insert padding between any member (e.g. in order to maintain alignment)
    • The representation of bit fields is unspecified. They may be placed in any order and do not respect any of the previous rules. Because you cannot take the address of a bit field, there is no mechanism to observe this.

    Specific standard references (emphasis mine):

    C++03 9.2 [class.mem]/12:

    Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1). 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).

    N3376 (the first post C++11 draft) 9.2 [class.mem]/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. 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).

    N3376 9.6 [class.bit]/1:

    [...] Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. [...]

    /3:

    [...] The address-of operator & shall not be applied to a bit-field, so there are no pointers to bitfields. [...]

提交回复
热议问题