C++ Memory layout of inheritance

偶尔善良 提交于 2019-12-14 03:53:27

问题


If I have two classes, one inheriting from the other, and the child class only containing functions, will the memory layout be the same for both classes?

e.g.

class Base {
  int a,b,c;
};

class Derived: public Base {
  // only functions.
};

I've read that the compiler can not reorder data members, and I do not require multiple-inheritance on the Derived class. Is there any situation where the memory layout will not be the same? (Multiple inheritance may be needed for the Base class)


回答1:


Both Base and Derived here are standard layout classes. Since standard layout is intended to for interoperation with other languages (most notably C), yes, you can expect the layout to be the same for both. If you add multiple-inheritance to the mix however, the result may or may not be a standard layout class. You can check the rules for that in the post linked above.




回答2:


The layout must be the same, because you can access derived instances through pointers to the base class.

Which means they would still be the same even if you had added data members.

Which also means it would've been the same even if you had used multiple inheritance.
(Although in that case, you might need to specifically do static_casts to specify which instance of the base you're referring to, since the derived class pointer need not be the same as the base class pointer.)




回答3:


It varies compiler to compiler, but I would think for the most common compilers your assumption would be correct. g++/gcc for certain work as you suggest, I'm not sure about other though.




回答4:


As they are, the layout of both classes is the same, but note that if you add any virtual function to the derived type, then the layout will change (or at least can change).

Now, from the description it seems that what you are trying to do is to create a type to provide member functions on top of an existing class, if that is the case, you should probably consider other different designs, like using free functions (C style).




回答5:


DON'T count on it.

But the memory layout might in fact be the same for some common compilers.



来源:https://stackoverflow.com/questions/11404209/c-memory-layout-of-inheritance

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