C++继承的虚拟类的内存布局

C++ memory layout of inherited virtual class

本文关键字:内存 布局 虚拟 继承 C++      更新时间:2023-10-16

关于派生类的大小,是有一个继承的"链"更好,还是继承最低派生类中的所有内容更好?

例如,以下两者之间有什么更好的:

class Base {
virtual void something() = 0;
};
class Derived1 {
// ...
};
class Derived2 : public Derived1, public Base {
// ...
};

class Base {
virtual void something() = 0;
};
class Derived1 : public Base {
// ...
};
class Derived2 : public Derived1 {
// ...
};

在第二种情况下,它是否必须存储两个 vtable 指针,在第一种情况下只有一个?

在第一种情况下,我的sizeof(Derived)比第二种情况低。

据我所知,您所看到的只是一个空的基类优化。
看看我准备的神霹雳。当您没有空类时,大小是相同的。

https://godbolt.org/z/HhiJz6

具体解决您的问题Regarding the size of the derived class, is it better to have a "chain" of inheritance or inherit everything in the lowest derived class?

我想如果你有一个空的基类,你可以声称它在类的大小方面"更好",但这在很大程度上取决于类定义方式的具体情况,这些方式可能随时更改。
我不会基于它建立继承结构,除非我真的需要空间。