为什么C ++中类的大小取决于数据成员的公共/私有状态? [英] Why does the size of class in c++ depend on the public/private status of data members?

查看:80
本文介绍了为什么C ++中类的大小取决于数据成员的公共/私有状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,C ++中类的大小取决于以下因素-

From what i know, the size of a class in c++ depends on the below factors -

  1. 所有非静态数据成员的大小.
  2. 数据成员的顺序.
  3. 是否启用了字节填充.
  4. 其直接基类的大小.
  5. 虚拟功能的存在.
  6. 继承方式(虚拟继承).

现在我已经创建了2个类,如下所示-

Now I've created 2 classes as below -

class A{
    int a;
    short s;
    int b;
    char d;
};// kept a char at last on purpose to leave a "hole"

class B : public A{
    char c;  
};

现在检查A和B的大小了

now on checking the size of A and B I see

  • A的大小:16
  • B的大小:16

我的假设是B类中的字符c容纳在A类中剩余的空洞"中.

my assumption is the char c in class B is accommodated in "hole" left in class A.

但是,让我感到困惑的是以下情况,我将成员公开

But, whats confused me is the below scenario wherein I make the members public

class A{
    public:
    int a;
    short d;
    int b;
    char s;
};

class B : public A{
    public:
    char c;
};

现在大小变为

  • A的大小:16
  • B的大小:20

我似乎无法理解这种差异的原因.

I cannot seem to understand the reason for this difference.

推荐答案

Itanium ABI 使用POD的C ++ 03定义定义用于布局目的的POD"类.拥有私有数据成员将使类失去聚合资格,因此无法在C ++ 03中实现POD:

The Itanium ABI uses the C++03 definition of POD to define classes that are "POD for the purposes of layout". Having private data members disqualifies a class from being an aggregate and therefore POD in C++03:

POD结构是没有非静态数据的聚合类 non-POD-struct,non-POD-union类型的成员(或此类类型的数组) 或引用,并且没有用户定义的副本分配运算符,也没有 用户定义的析构函数.

A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor.

成为POD类禁用尾部填充重用 :

这些类型的dsize,nvsize和nvalign被定义为其 普通尺寸和对齐方式.这些属性仅对 用作基类的非空类类型.我们忽略尾巴 填充POD,因为该标准的早期版本没有 允许我们将其用于其他任何用途,因为它有时会允许 更快地复制类型.

The dsize, nvsize, and nvalign of these types are defined to be their ordinary size and alignment. These properties only matter for non-empty class types that are used as base classes. We ignore tail padding for PODs because an early version of the standard did not allow us to use it for anything else and because it sometimes permits faster copying of the type.

因此,在您的第一个示例中,A不是用于布局目的的POD,并且其尾部填充可用于B::c,但是在您的第二个示例中,它是POD,并且其尾部填充无法重复使用

Thus, in your first example, A is not a POD for layout purposes and its tail padding can be used for B::c, but in your second example, it is a POD, and its tail padding cannot be reused.

这篇关于为什么C ++中类的大小取决于数据成员的公共/私有状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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