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

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

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)