gpt4 book ai didi

c++ - 如果与基类相比没有新的成员变量,C++ 是否允许增加派生类的大小?

转载 作者:IT老高 更新时间:2023-10-28 14:00:55 26 4
gpt4 key购买 nike

假设我有一个包含一些成员变量但没有虚函数的基类:

class Base {
int member;
};

以及从 Base 以非虚拟方式派生的派生类,并且没有新的成员变量,也没有虚拟函数:

class Derived : Base {
};

显然 sizeof(Derived) 不能小于 sizeof(Base)

sizeof(Derived)是否必须等于sizeof(Base)

最佳答案

从 5.3.2 [expr.sizeof]

When applied to a class, the result [of sizeof] is the number of bytes in an object of that class including any padding required for placing objects of that type in an array. The size of a most derived class shall be greater than zero (1.8).

从 1.8 [intro.object]

Unless it is a bit-field (9.6), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class sub-objects may have zero size. An object of POD type (3.9) shall occupy contiguous bytes of storage.

还有一个注释:

The actual size of a base class subobject may be less than the result of applying sizeof to the subobject, due to virtual base classes and less strict padding requirements on base class subobjects.

将这些放在一起,我认为它告诉您的是,您无法保证 sizeof 可能会告诉您什么,除了结果将大于零。事实上,它甚至似乎不能保证 sizeof(Derived) >= sizeof(Base)!

关于c++ - 如果与基类相比没有新的成员变量,C++ 是否允许增加派生类的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19949737/

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