如果 base class 没有成员,派生的 C++ class 的大小是多少?

What will be the size of derived C++ class if base class has no members?

考虑以下继承:

class Base {
protected:
  Base() { }
public:
  double Multiply(double x);
};

class Derived : public Base {
  double _value;
public:
  Derived(double init) : _value(init) { }
  double Multiply(double x) { return x*_value; }
};

此代码段将用于模板化代码库。多态性不是一个选项,因为它添加了 VTable 指针,从而使内存消耗加倍。

但是,我怀疑由于 C++ 要求对象的大小至少为 1 个字节,Derived 的大小将变为 9 个字节,因此,由于 padding/alignment 它将进一步变成16字节。

那么在 C++ 中有没有办法让 Derived 的大小等于 double 的大小(通常是 8 个字节)? 标准对 Derived 的大小有何规定? 特别是,MSVC++ 在这种情况下的表现如何?

这叫做空基优化,在标准中定义如下:

1.8 The C ++ object model [intro.object]

7 Unless it is a bit-field (9.2.4), a most derived object shall have a nonzero size and shall occupy one or more bytes of storage. Base class subobjects may have zero size. An object of trivially copyable or standard-layout type (3.9) shall occupy contiguous bytes of storage.

8 Unless an object is a bit-field or a base class subobject of zero size, the address of that object is the address of the first byte it occupies. Two objects a and b with overlapping lifetimes that are not bit-fields may have the same address if one is nested within the other, or if at least one is a base class subobject of zero size and they are of different types; otherwise, they have distinct addresses.

在您的示例中,继承 Base class 不会影响 Derived class 的大小。然而,MSVC++ 仅对第一个空基 class 执行此类优化,因此继承空基 classes 将导致 Derived class 大小的增长。我相信长期以来,这一直是对 MSVC++ 的批评点,因为许多其他编译器没有这个问题。如果你有很多小辅助 classes,这真的很麻烦。作为解决方法,派生模板基 class 可用于将多重继承转换为单一继承链:

class Base1
{};

template< typename TBase > class Base2: public TBase
{};

template< typename TBase > class Base3: public TBase
{};

class Derived: public Base3< Base2< Base1 > >
{};

MS Connect bug page。看来他们毕竟不是要修复它。