我想知道空类对象的大小.它肯定可以不为 0 字节,因为它应该可以像任何其他对象一样引用和指向它.但是,这样的物体有多大?
I was wondering what could be the size of an object of an empty class. It surely could not be 0 bytes since it should be possible to reference and point to it like any other object. But, how big is such an object?
我用过这个小程序:
#include <iostream>
using namespace std;
class Empty {};
int main()
{
Empty e;
cerr << sizeof(e) << endl;
return 0;
}
我在 Visual C++ 和 Cygwin-g++ 编译器上得到的输出是 1 字节!这让我有点惊讶,因为我期望它是机器字的大小(32 位或 4 字节).
The output I got on both Visual C++ and Cygwin-g++ compilers was 1 byte! This was a little surprising to me since I was expecting it to be of the size of the machine word (32 bits or 4 bytes).
谁能解释为什么 1 个字节的大小?为什么不 4 个字节?这也取决于编译器还是机器?另外,有人可以给出一个更令人信服的理由来解释为什么空类对象不会的大小为 0 字节?
Can anyone explain why the size of 1 byte? Why not 4 bytes? Is this dependent on compiler or the machine too? Also, can someone give a more cogent reason for why an empty class object will not be of size 0 bytes?
引用 Bjarne Stroustrup 的 C++Style and Technique FAQ,大小不为零的原因是为了确保两个不同对象的地址不同".大小可以是 1,因为对齐在这里并不重要,因为实际上没有什么可看的.
Quoting Bjarne Stroustrup's C++ Style and Technique FAQ, the reason the size is non-zero is "To ensure that the addresses of two different objects will be different." And the size can be 1 because alignment doesn't matter here, as there is nothing to actually look at.
这篇关于C++:空类的对象的大小是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!