gpt4 book ai didi

c++ - 如果基类没有成员,派生 C++ 类的大小是多少?

转载 作者:搜寻专家 更新时间:2023-10-31 00:09:16 26 4
gpt4 key购买 nike

考虑以下继承:

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 个字节,因此,由于填充/对齐,它将进一步变为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 类不会影响 Derived 类的大小。然而,MSVC++ 仅对第一个空基类执行此类优化,因此从其他空基类继承将导致 Derived 类大小的增长。我相信长期以来,这一直是对 MSVC++ 的批评点,因为许多其他编译器没有这个问题。如果你有很多小的辅助类,这真的很麻烦。作为解决方法,可以使用派生模板基类将多重继承转换为单一继承链:

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 .看起来他们毕竟不是要修复它。

关于c++ - 如果基类没有成员,派生 C++ 类的大小是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44187821/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com