C++:空类的对象的大小是多少?

C++: What is the size of an object of an empty class?(C++:空类的对象的大小是多少?)
本文介绍了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?

我用过这个小程序:

#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++:空类的对象的大小是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)