C ++继承的内存布局 [英] C++ Memory layout of inheritance

查看:96
本文介绍了C ++继承的内存布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个类,一个类继承自另一个类,而子类仅包含函数,那么两个类的内存布局是否相同?

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?

例如

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

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

我已阅读到编译器无法对数据成员进行重新排序,并且我不需要对Derived类进行多重继承.有什么情况下内存布局会不同吗? (Base类可能需要多重继承)

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)

推荐答案

BaseDerived均在此处

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.

这篇关于C ++继承的内存布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆