空类的大小 [英] Sizeof empty class

查看:31
本文介绍了空类的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用代码:

#include <iostream>

class A {};
class B { char x; };

int main()
{
    std::cerr << sizeof(A) << " " << sizeof(B) << std::endl;
}

我知道问一个空班级的人数是一个常见的面试问题-我知道答案是一个.

I know that it's a common interview question to ask the size of an empty class - and I know the answer is one.

我的问题是...空类的"1"字节中保存了什么(我猜它为空),并且编译器在内部进行了哪些操作以使 sizeof B sizeof A 相同吗?

My question is... what is held in that "1" byte for an empty class (I'm guessing its empty), and what does the compiler do internally to make it so that sizeof B is the same as sizeof A in this case?

我想完全理解它,而不只是知道答案.

I'd like to fully understand it rather than just know the answer.

推荐答案

这并不是一个有意义的问题:运行时仅将一个字节标记为已占用,因此不会在其位置分配任何其他对象.但是那里什么也没有占据"来占据字节.

This isn’t really a meaningful question: The runtime just marks the one byte as occupied so that no other object will be allocated at its position. But there isn’t anything "held" there to occupy the byte.

此规则的唯一原因是对象必须是唯一可识别的.对象由其在内存中的地址标识.为了确保没有两个对象具有相同的地址(基类对象除外),空类的对象通过具有非零的大小来占用"内存.

The only reason for this rule is that objects must be uniquely identifiable. An object is identified by the address it has in memory. To ensure that no two objects have the same address (except in the case of base class objects), objects of empty classes "occupy" memory by having a non-zero size.

这篇关于空类的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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