为什么sizeof一个empty class的结果是1
来源:互联网 发布:js style.marginleft 编辑:程序博客网 时间:2024/06/05 17:27
#include<iostream>class Empty{};int main( int argc, char* argv[] ){ std::cout << "sizeof(Empty) is " << sizeof(Empty) << std::endl; return 0;}
上面的代码会出现在很多的笔试题纸上,那么它在标准输出上输出什么呢?在大多数的编译器上,输出的结果是:
sizeof(Empty) is 1
可是为什么呢?Empty是一个没有数据成员的类,但C++标准还是允许我们去声明一个该类的对象的,因为参考C++标准(ISO/IEC 14882:n3242):在1.8 The C++ object model里写道:"An object is a region of storage.""An object is created by a definition, by a new-expression or by the implementation when needed."可见在C++里,对象的实质就是一块存取空间。接着标准里提到:"Unless it is a bit-field, a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class subobjects may have zero size."可见一个对象的大小应当是非零的。接着标准提到:"Unless an object is a bit-field or a base class subobject of zero size, the address of that object is the address of the first byte it occupies. Two distinct objects that are neither bit-fields nor base class subobjects of zero size shall have distinct addresses."可见,不同的对象,其占用的存取地址不一样。结合以上几点,可知C++编译器使用了一个dummy byte去区别类Empty的不同对象,同时也保证了对象的大小非零的规则。至于该dummy byte的内容,则由编译器来决定了。而且,编译器不一定非要用一个dummy byte来表示类Empty的一个对象,也可以用两个或更多,只是一个比较省空间罢了。
0 0
- 为什么sizeof一个empty class的结果是1
- why 1 byte of sizeof empty class
- 为什么这个程序中sizeof的结果是4…
- sizeof('a')的结果是多少?
- 为什么结果是一样的?
- c++中包含empty virtual base class 类的sizeof结果分析
- What?一个rand都没有,然而为什么演示结果是随机的???
- JAVA-----疑问1:为什么结果是0
- class的sizeof
- class的sizeof
- class的sizeof
- sizeof(数组名)和sizeof(指针名)的结果是不同的
- 为什么输出结果是3
- 在 JavaScript 中为什么 typeof null 的结果是 object?
- Empty Class(空类)的作用
- 关于sizeof(Class)的学习
- class类的sizeof计算
- C++ class的各种sizeof
- Unity手游之路<九>自动寻路Navmesh之高级主题
- ffmpeg 实现音频aac编码
- MVC实现通用的增删改查。使用接口(三)学习
- Mysql数据库学习
- Android抓包工具tcpdump使用教程(整理)
- 为什么sizeof一个empty class的结果是1
- poj2197||zoj2406 Jill's Tour Paths(回溯+优先队列)
- Android NDK之----- C调用Java [GetMethodID方法的使用]
- ,net 3.5到.net4.0的登录页面无法跳转的问题
- 前世今生之linux内存管理
- FZU 2150 Fire Game
- Dos 怎么获取当前路径
- WebSocket与Java
- 读书札记-2013年12月