Classes store data members in sequential memory?

后端 未结 1 1431
余生分开走
余生分开走 2021-01-21 05:57

The short version of this question: Does a pointer to the first data member of a class result in a pointer to all its data members?

Discussion:

I\'m reading some

1条回答
  •  失恋的感觉
    2021-01-21 06:22

    This is the C++ object model. You're guaranteed that within the same access level (private/public/protected), the object properties are in order (C++11), and the same for members without access specifiers between them (in C++03).

    This doesn't mean what you're doing is a good idea. It's better to avoid the cast and just have the function do some more work.

    C++11:

    9.2 Class members [class.mem]

    14) 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 (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).

    C++03

    9.2 Class members [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 non-static 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).

    0 讨论(0)
提交回复
热议问题