c++ data alignment /member order & inheritance

后端 未结 9 1643
礼貌的吻别
礼貌的吻别 2020-11-29 01:34

How do data members get aligned / ordered if inheritance / multiple inheritance is used? Is this compiler specific?

Is there a way to specify in a derived class how

9条回答
  •  孤城傲影
    2020-11-29 02:07

    The order of objects in multiple inheritance is not always what you specify. From what I've experienced, the compiler will use the specified order unless it can't. It can't use the specified order when the first base class does not have virtual functions and another base class has virtual functions. In this case, the first bytes of the class has to be a virtual function table pointer, but the first base class doesn't have one. The compiler will rearrange the base classes so that the first one has a virtual function table pointer.

    I've tested this with both msdev and g++ and both of them rearrange the classes. Annoyingly, they seem to have different rules for how they do it. If you have 3 or more base classes and the first one doesn't have virtual functions, these compilers will come up with different layouts.

    To be safe, pick two and avoid the other.

    1. Don't rely on the ordering of base classes when using multiple inheritance.

    2. When using multiple inheritance, put all base classes with virtual functions before any base classes without virtual functions.

    3. Use 2 or fewer base classes (since the compilers both rearrange in the same way in this case)

提交回复
热议问题