C++:空类的对象的大小是多少?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/621616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++: What is the size of an object of an empty class?
提问by Ashwin Nanjappa
I was wondering what could be the size of an object of an empty class. It surely could notbe 0 bytes since it should be possible to reference and point to it like any other object. But, how big is such an object?
我想知道空类的对象的大小可能是多少。它肯定不能是 0 字节,因为它应该可以像任何其他对象一样引用和指向它。但是,这样的物体有多大?
I used this small program:
我用了这个小程序:
#include <iostream>
using namespace std;
class Empty {};
int main()
{
Empty e;
cerr << sizeof(e) << endl;
return 0;
}
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).
我在 Visual C++ 和 Cygwin-g++ 编译器上得到的输出都是1 个字节!这对我来说有点令人惊讶,因为我期望它具有机器字的大小(32 位或 4 字节)。
Can anyone explain whythe size of 1 byte? Why not4 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 notbe of size 0 bytes?
谁能解释为什么1 个字节的大小?为什么不是4 个字节?这也取决于编译器还是机器?另外,有人可以给出一个更令人信服的理由来说明为什么空类对象的大小不会为 0 字节吗?
回答by Sol
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.
引用Bjarne Stroustrup 的 C++ Style and Technique FAQ,大小非零的原因是“为了确保两个不同对象的地址不同。” 大小可以是 1,因为对齐在这里并不重要,因为实际上没有什么可看的。
回答by TrayMan
The standard states that all most derived objects have sizeof() >= 1:
标准规定所有大多数派生对象的 sizeof() >= 1:
Unless it is a bit-field (class.bit), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class sub-objects may have zero size. ISO/IEC FDIS 14882:1998(E) intro.object
除非它是位域 (class.bit),否则最衍生的对象应具有非零大小并应占用一个或多个字节的存储空间。基类子对象的大小可能为零。 ISO/IEC FDIS 14882:1998(E) intro.object
回答by paxdiablo
That's really an implementation detail. Once long ago, I thought it could be zero bytes or a thousand bytes, that it has no bearing on the language specification. But, after looking at the standard (section 5.3.3), sizeof
is defined as always returning one or greater, no matter what.
这确实是一个实现细节。很久以前,我认为它可能是零字节或一千字节,它与语言规范无关。但是,在查看标准(第 5.3.3 节)之后,sizeof
被定义为始终返回 1 或更大的值,无论如何。
The size of a most derived class shall be greater than zero.
最派生类的大小应大于零。
This is required for, among other things, allowing you to handle arrays of objects and pointers to them. If your elements were allowed to be zero-sized then &(array[0])
would be identical to &(array[42])
, which is going to cause all sorts of havoc to your processing loops.
这是必需的,除其他外,允许您处理对象数组和指向它们的指针。如果您的元素被允许为零大小,那么&(array[0])
将与 相同&(array[42])
,这将对您的处理循环造成各种破坏。
The reason why it may not be a machine word is that there are no elements within it that actually require it to be aligned on a word boundary (such as an integer). For example, if you place char x; int y;
inside the class, my GCC clocks it at eight bytes (since the second int must be aligned in that implementation).
它可能不是机器字的原因是其中没有元素实际上需要它在字边界上对齐(例如整数)。例如,如果您放置char x; int y;
在类中,我的 GCC 以 8 个字节计时(因为第二个 int 必须在该实现中对齐)。
回答by Konstantin Nikitin
There is an exception: 0-length arrays
有一个例外:长度为 0 的数组
#include <iostream>
class CompletlyEmpty {
char NO_DATA[0];
};
int main(int argc, const char** argv) {
std::cout << sizeof(CompletlyEmpty) << '\n';
}
回答by lalatendu
Even though its not required to assign any memory for an empty class, but in order to make objects of empty classes, compiler assigns the minimum memory that can be assigned, which is 1 byte. This way compiler can distinguish two objects of the same empty class uniquely, and will able to assign the address of the object to a pointer of the empty class type.
尽管不需要为空类分配任何内存,但是为了制作空类的对象,编译器分配了可以分配的最小内存,即1个字节。这样编译器就可以唯一区分同一个空类的两个对象,并将对象的地址分配给一个空类类型的指针。
回答by Johannes Schaub - litb
I think it might be helpful to link to an answer explaining this good too. It isabout boost::compressed_pair
by Logan Capaldo.
我认为链接到解释这个好处的答案也可能会有所帮助。这是关于boost::compressed_pair
由洛根卡帕尔多。
回答by Arsalan Mehmood
This may help u :-) http://bytes.com/topic/c/insights/660463-sizeof-empty-class-structure-1-a
这可能会帮助你 :-) http://bytes.com/topic/c/insights/660463-sizeof-empty-class-structure-1-a
The sizeof an empty class or structure is 1
The reason this happens boils down to properly implementing the standard, one of the things the C++ standard says is that "no object shall have the same address in memory as any other variable".... What is the easiest way to ensure this? Make sure that all types have a non-zero size. In order to achieve this the compiler adds a dummy byte to structures and classes that have no data members and no virtual functions so that they have a size of 1 rather than a size of 0 and then they are guaranteed to have a unique memory address.
空类或结构的大小为 1
发生这种情况的原因归结为正确实现标准,C++ 标准所说的一件事是“任何对象在内存中都不应具有与任何其他变量相同的地址”......确保这一点的最简单方法是什么?确保所有类型的大小都非零。为了实现这一点,编译器向没有数据成员和虚函数的结构和类添加了一个虚拟字节,以便它们的大小为 1 而不是大小为 0,然后保证它们具有唯一的内存地址。
回答by user332764
Allocation of 1 byte for an empty class is compiler dependent. Compilers need to make sure objects reside in different memory locations and they need to allocate non zero memory size to an object. Listen to notes on this topic here: http://listenvoice.com/listenVoiceNote.aspx?id=27
为空类分配 1 个字节取决于编译器。编译器需要确保对象驻留在不同的内存位置,并且需要为对象分配非零内存大小。在此处收听有关此主题的说明:http: //listenvoice.com/listenVoiceNote.aspx?id=27
Even though compilers allocates non zero size to an empty class they also do optimizations when new classes are derived from empty classes. Listen about empty base optimization on ListenVoice's c++ programming interview questions.
即使编译器为空类分配非零大小,它们也会在从空类派生新类时进行优化。在 ListenVoice 的 c++ 编程面试问题中聆听空基优化。
回答by Ramiz
the reason for class with no data members but having size 1 byte is that the this*strong text* must be stored in memory so that a reference or pointer can point to the object of that class
没有数据成员但大小为 1 字节的类的原因是 this*强文本* 必须存储在内存中,以便引用或指针可以指向该类的对象
回答by kidfisto
I think this question is only of theoretical interest but doesn't matter in practice.
我认为这个问题仅具有理论意义,但在实践中并不重要。
As already pointed out by others, deriving from an empty class doesn't do any harm, as this will not consume any extra memory for the base class portion.
正如其他人已经指出的那样,从空类派生不会造成任何伤害,因为这不会为基类部分消耗任何额外的内存。
Moreover, if a class is empty (meaning that it - theoretically - doesn't need any per-instance memory, i.e. it doesn't have any non-static data members or virtual member functions) then all its member functions can just as well (and should) be defined as static. So there is no need to ever create an instance of this class.
此外,如果一个类是空的(这意味着它 - 理论上 - 不需要任何实例内存,即它没有任何非静态数据成员或虚拟成员函数)那么它的所有成员函数也可以(并且应该)被定义为静态。所以没有必要创建这个类的实例。
Bottom line: If you find yourself writing an empty class X then just make all member functions static. You then won't need to create X objects, and derived classes will not be affected in any way.
底线:如果您发现自己编写了一个空类 X,那么只需将所有成员函数设为静态即可。这样您就不需要创建 X 对象,并且派生类不会受到任何影响。