c++ - 没有数据的类的对象是否占用内存?

标签 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. The void type is an incomplete type that cannot be completed.

(C++11 §3.9.1 ¶9)

关于c++ - 没有数据的类的对象是否占用内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14092284/

相关文章:

c++ - 为什么 C++ 允许通过指针访问类的私有(private)成员?

C++ STL 比较映射找不到(运算符==)

c++ - 将 const ref 分配给非常量对象

c++ - 返回间接类型对象会影响性能吗?

c++ - 如何向用户显示特定错误,要求他/她使用循环再次提供输入?

c++ - 为什么即将推出的范围库不支持范围内的容器初始化?

C++ std::system 'system' 不是 std 的成员

c++ - 克利昂 2016.3 : switch to "Release" configuration

c++ - CUDA 推力返回类型

c++ - 使用 boost::hana 传递反射