如果与基类相比没有新的成员变量,C ++是否允许增加派生类的大小? [英] Is C++ allowed to increase the derived class size if there're no new member variables compared to the base class?

查看:157
本文介绍了如果与基类相比没有新的成员变量,C ++是否允许增加派生类的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a base class with some member variables and no virtual functions:

class Base {
   int member;
};

和一个以非虚拟方式从 / code>并且没有新的成员变量,没有虚函数:

and a derived class that derives in a non-virtual way from Base and has no new member variables an again no virtual functions:

class Derived : Base {
};

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

c $ c>需要等于 sizeof(Base)

推荐答案

p>从5.3.2 [expr.sizeof]

From 5.3.2 [expr.sizeof]


应用于类时,结果[of sizeof ]是该类的对象中的字节数,包括将该类型对象放入数组所需的任何填充。最诱导类的大小应大于零(1.8)。

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]

From 1.8 [intro.object]


除非是位字段(9.6),最导出的对象应具有非零大小,并且将占用一个或多个字节的存储空间。基类子对象可以具有零大小。 POD类型(3.9)的对象将占用连续的存储字节。

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.

和注意:


基类子对象的实际大小可能小于将sizeof应用于子对象的结果,因为虚基类和对基类子对象的填充要求不太严格。

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)

Put these together and I think what it's telling you is that you have no guarantees whatsoever as to what sizeof might tell you, other than the result will be greater than zero. In fact, it doesn't even seem to guarantee that sizeof(Derived) >= sizeof(Base)!

这篇关于如果与基类相比没有新的成员变量,C ++是否允许增加派生类的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆