【发布时间】: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) 低于第二种情况。
【问题讨论】:
-
这取决于设计和要求。如果
Base将被其他派生类重用,那么它是必要的,因为它可以为它们实现所有常见功能。如果没有这样的需要,那么您当然可以使用 MI。每个父类都有一个单独的vtbl,但这是特定于实现的。虚拟表不应该直接可见或可用。 -
根据您在第一个类中所做的事情,您可能会看到空基类优化
-
有趣的是,如果
Derived1有任何虚成员函数,the "big three" compilers will actually use less space for the second case than the first, because they like to reuse vtables whenever they can。使用 MSVC 的布局输出最容易看到,但您可以通过一些筛选在其他两个中找到大小。
标签: c++ inheritance abstract-class