【问题标题】:C++ memory layout of inherited virtual class继承的虚拟类的C++内存布局
【发布时间】:2020-09-30 07:35:03
【问题描述】:

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

例如,以下之间哪个更好:

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) 低于第二种情况。

【问题讨论】:

标签: c++ inheritance abstract-class


【解决方案1】:

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

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?

我猜如果你有一个空的基类,你可以声称它在类的大小方面“更好”,但这很大程度上取决于类定义方式的细节可能会改变随时。
除非我真的真的需要空间,否则我不会基于它建立继承结构。

【讨论】:

    猜你喜欢
    • 2015-09-01
    • 1970-01-01
    • 2012-07-21
    • 2023-03-13
    • 2015-04-15
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多