<分区>
Possible Duplicate:
C++: What is the size of an object of an empty class?
我有一个没有数据的类如下
class A {};
我用它来定义一个对象
A a;
我认为对象“a”有一个地址,对吧?它占用一些内存吗?如果是,它占用多少字节?
如果对象“a”的类型为 void 会发生什么。非常感谢!
标签 c++
<分区>
Possible Duplicate:
C++: What is the size of an object of an empty class?
我有一个没有数据的类如下
class A {};
我用它来定义一个对象
A a;
我认为对象“a”有一个地址,对吧?它占用一些内存吗?如果是,它占用多少字节?
如果对象“a”的类型为 void 会发生什么。非常感谢!
最佳答案
I think object "a" has an address, right? Does it occupy some memory? If so, how many bytes it occupy?
IIRC 标准要求每个对象都有一个地址,并且对象的最小大小(由 sizeof
返回)为 1。话虽如此,优化器可能会使该变量消失(也许除非你明确要求它的地址)。
Unless it is a bit-field (9.6), 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.4
Note 4: Under the “as-if” rule an implementation is allowed to store two objects at the same machine address or not store an object at all if the program cannot observe the difference (1.9).
(C++11 §1.8 ¶5-6)
What happens if object "a" with a type void.
void
不能用于声明变量,因为它是“不完整类型”。
The
void
type has an empty set of values. Thevoid
type is an incomplete type that cannot be completed.
(C++11 §3.9.1 ¶9)
关于c++ - 没有数据的类的对象是否占用内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14092284/