简体   繁体   English

C ++继承的内存布局

[英]C++ Memory layout of inheritance

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? 如果我有两个类,一个继承自另一个类,而子类只包含函数,那么这两个类的内存布局是否相同?

eg 例如

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. 我已经读过编译器不能重新排序数据成员,并且我不需要在Derived类上进行多重继承。 Is there any situation where the memory layout will not be the same? 是否存在内存布局不一样的情况? (Multiple inheritance may be needed for the Base class) Base类可能需要多重继承)

Both Base and Derived here are standard layout classes . BaseDerived 都是标准布局类 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. 由于标准布局旨在与其他语言(最值得注意的是C)进行互操作,是的,您可以预期两者的布局相同。 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. 您可以在上面链接的帖子中查看相关规则。

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_cast s 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.) (虽然在这种情况下,您可能需要专门执行static_cast来指定您引用的基类的哪个实例 ,因为派生类指针不需要与基类指针相同。)

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. g ++ / gcc对于某些工作你的建议,我不确定其他的。

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). 现在,从描述看来,你要做的就是创建一个类型来在现有类之上提供成员函数,如果是这种情况,你应该考虑其他不同的设计,比如使用自由函数(C样式)。

DON'T count on it. 不要指望它。

But the memory layout might in fact be the same for some common compilers. 但是对于一些常见的编译器来说,内存布局实际上可能是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM