为什么sizeof一个empty class的结果是1

来源:互联网 发布:js style.marginleft 编辑:程序博客网 时间:2024/06/05 17:27
#include<iostream>class Empty{};int main( int argc, char* argv[] ){    std::cout << "sizeof(Empty) is " << sizeof(Empty) << std::endl;    return 0;}


上面的代码会出现在很多的笔试题纸上,那么它在标准输出上输出什么呢?在大多数的编译器上,输出的结果是:

sizeof(Empty) is 1

可是为什么呢?

Empty是一个没有数据成员的类,但C++标准还是允许我们去声明一个该类的对象的,因为参考C++标准(ISO/IEC 14882:n3242):在1.8 The C++ object model里写道:"An object is a region of storage.""An object is created by a definition, by a new-expression or by the implementation when needed."

可见在C++里,对象的实质就是一块存取空间。接着标准里提到:"Unless it is a bit-field, a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class subobjects may have zero size."可见一个对象的大小应当是非零的。接着标准提到:"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 distinct objects that are neither bit-fields nor base class subobjects of zero size shall have distinct addresses."可见,不同的对象,其占用的存取地址不一样。结合以上几点,可知C++编译器使用了一个dummy byte去区别类Empty的不同对象,同时也保证了对象的大小非零的规则。至于该dummy byte的内容,则由编译器来决定了。而且,编译器不一定非要用一个dummy byte来表示类Empty的一个对象,也可以用两个或更多,只是一个比较省空间罢了。

0 0