为什么 C++ 中空类的大小是这样的?不为零?
可能的重复:
C++:一个的大小是多少空类的对象?
为什么下面的输出是1
?
#include <iostream>
class Test
{
};
int main()
{
std::cout << sizeof(Test);
return 0;
}
Possible Duplicate:
C++: What is the size of an object of an empty class?
Why does the following output 1
?
#include <iostream>
class Test
{
};
int main()
{
std::cout << sizeof(Test);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
该标准不允许对象(及其类)的大小为 0,因为这将使两个不同的对象可能具有相同的内存地址。这就是为什么即使是空类的大小也必须(至少)为 1。
The standard does not allow objects (and classes thereof) of size 0, since that would make it possible for two distinct objects to have the same memory address. That's why even empty classes must have a size of (at least) 1.
请参阅 Stroustrup 获取完整答案。
See Stroustrup for complete answer.
C++ 标准保证任何类的大小至少为 1。 C++ 标准规定,任何对象都不得与另一个对象具有相同的内存地址。这有几个很好的理由。
保证
new
始终返回指向不同内存地址的指针。避免某些被零除的情况。例如,指针算术(其中许多由编译器自动完成)涉及除以
sizeof(T)
。但请注意,这并不意味着空基类会将派生类的大小加 1:
Bjarne Stroustrup 也谈到了这一点。
The C++ standard guarantees that the size of any class is at least one. The C++ standard states that no object shall have the same memory address as another object. There are several good reasons for this.
To guarantee that
new
will always return a pointer to a distinct memory address.To avoid some divisions by zero. For instance, pointer arithmetics (many of which done automatically by the compiler) involve dividing by
sizeof(T)
.Note however that it doesn't mean that an empty base-class will add 1 to the size of a derived class:
Bjarne Stroustrup talks about this too.
没有任何数据成员和成员函数的类称为空类。空类对象的大小始终为 1 个字节。
当我们创建任何类的对象时,对象总是具有 3 个特征,即
当我们创建空类的对象时,该对象的状态什么都没有。该对象的行为也没什么,但编译器为该对象分配了一个唯一的地址。
计算机中的内存始终以字节的形式组织,对象地址位置的最小可用内存为 1 字节。这就是为什么空类的对象大小是 1 字节的原因。
Class without any data members and member function such type of class is known as empty class. Size of object of empty class is always 1 byte.
When we create object of any class at that time object always gets 3 characteristics i.e.
When we create object of empty class at that time State of that object is nothing. Behaviour of that object is also nothing, but compiler assigns a unique address to that object.
Memory in Computer is always organized in the form of bytes and minimum memory available at object address location is 1 byte. That's why size of object of empty class is 1 byte.
莫里茨和彼得说的话。
有趣的是,在这种情况下,编译器可以进行空基类优化(EBCO):
如果编译并运行它,这可能会打印“1,1”。另请参阅Vandevoorde EBCO 上的 /Josuttis 16.2。
What Maurits and Péter said.
It is interesting to note in this context that compilers can do empty base class optimization (EBCO):
This will probably print "1,1" if you compile and run it. See also Vandevoorde/Josuttis 16.2 on EBCO.