简体   繁体   English

Sizeof空类

[英]Sizeof empty class

With the code: 随着代码:

#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. 我知道要问一个空课的大小是一个常见的面试问题 - 我知道答案是一个。

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? 我的问题是......在一个空类的“1”字节中保存了什么(我猜它是空的),编译器在内部做了什么来使它成为sizeof Bsizeof A相同案件?

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. 为了确保没有两个对象具有相同的地址(基类对象除外),空类对象通过具有非零大小来“占用”存储器。

There is no requirement in the C++ standard that an empty object should have one byte of memory occupied. 在C ++标准中没有要求空对象应该占用一个字节的内存。 It is purely based on the implementation. 它纯粹基于实现。

EDIT: true, it's conforming ( ISO/IEC 14882 p.149 ): 编辑:是的,符合(ISO / IEC 14882第149页):

9 Classes [class] 9个班级[班级]
.. ..
.. ..
.. ..
3 Complete objects and member subobjects of class type shall have nonzero size ... 3类类型的完整对象和成员子对象应具有非零大小...

You can often see a similar effect in classes like these : 您经常可以在类中看到类似的效果:

class Foo {
  int a;
  char b;
}; // sizeof(Foo) > sizeof(int) + sizeof(char)

Not all memory in a C++ object needs to have a name. 并非C ++对象中的所有内存都需要具有名称。 Unnames memory inside an object is commnoly called "padding". 在对象内部取消命名内存是通用的称为“填充”。 Your empty class happens to have one byte of padding. 您的空类恰好有一个填充字节。 One of the most common reasons why C++ compilers insert padding is to allow use of a class in an array type. C ++编译器插入填充的最常见原因之一是允许在数组类型中使用类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM