为什么从两个空类派生的空类的大小是2? [英] Why the size of empty class that is derived from two empty classes is 2?

查看:324
本文介绍了为什么从两个空类派生的空类的大小是2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所知道的是,空类的大小为1只是为了符合不允许大小为0的对象(及其类)的标准。这里,我得到派生类D的大小为2。为什么行为在这种情况下是不同的
,假设没有数据成员或虚拟指针继承自B类和C到D?

What I know is that size of empty class is 1 just to conform to the standard that does not allow objects (and classes thereof) of size to be 0. Here, I am getting size of a derived class D as 2. Why behavior is different in this case given that there is no data member or virtual pointer inherited from class B and C to D?

#include<iostream>
using namespace std;

class A {};
class B : public A {};
class C : public A {};
class D : public B, public C {};

int main() {
    cout<<"Size of D is: "<<sizeof(D)<<endl;
    return 0;
}


推荐答案

对我来说似乎是否或者不在这里应用空基础优化,取决于如何解释 [intro。 object / 8]

To me it seems that whether or not the empty base optimization can be applied here, depends on how one interprets [intro.object/8]:


除非对象是零字段或零基础子对象零
size,该对象的地址是
占据的第一个字节的地址。 两个对象 a和b的重叠生命周期不是
位字段如果一个嵌套在
other中,或者至少有一个,则可能具有相同的地址是一个零大小的基类子对象和
它们是不同类型的
;否则,他们有不同的地址。

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.

B C 不同的类型?它们都是 A 。实际上有两个不同的 A 对象。允许编译器编写器单独停止 B C 的分配存储,而不检查 A 是空的。

Are B and C different types? They both are an A as well. Two distinct A objects actually. A compiler writer is allowed to stop right there an allocate storage for B and C separately, without checking that A is empty.

值得注意的是,如果你有,使用g ++时,大小会回到1 B C 继承自单独的基础:

It's worth noting that with g++ the size is back to 1 if you have B and C inherit from separate bases:

实例

#include<iostream>

class A  {};
class A1 {};
class B : public A {};
class C : public A1 {};
class D : public B, public C {};

int main() {
    std::cout << "Size of D is: " << sizeof(D) << std::endl;
    return 0;
}

这篇关于为什么从两个空类派生的空类的大小是2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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