C++: What is the size of an object of an empty class?(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++:空类的对象的大小是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++:空类的对象的大小是多少?


基础教程推荐
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04