What is the C++ memory layout of objects/structs etc?

前端 未结 2 668
小鲜肉
小鲜肉 2021-01-20 21:10

In C++ I presume the C++ standard has nothing to do with how data members are arranged within a class, in terms of memory layout? Would I be right in thinking this is down t

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-20 21:56

    The C++ standard does specify a few things, but far from everything.

    The main rules are these:

    • objects in an array are laid out contiguously, with no padding between them.
    • class member objects not separated by an access specifier (public:/private:/protected:) are laid out in memory in the order in which they're declared, but there may be an unspecified amount of padding between member objects.
    • for certain types (standard-layout structs, in standardese terminology), the first base class, or if none exists, the first member, is laid out at the same address that the class itself.

    There are a few more bits and pieces specified by the standard, but on the whole, the remaining details are really down to the compiler.

提交回复
热议问题