C ++:一个空类的对象的大小是多少? [英] C++: What is the size of an object of an empty class?

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

问题描述

我想知道什么是空类的对象的大小。它肯定可以不是为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?

I used this small program:

c $ c> #include< iostream>
using namespace std;

class Empty {};

int main()
{
Empty e;
cerr<< sizeof(e) endl;
return 0;
}

#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 ++风格和技巧常见问题,原因大小为非零是确保两个不同对象的地址将不同。尺寸可以是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 ++:一个空类的对象的大小是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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