为什么没有成员变量的C ++类占用空间? [英] Why do C++ classes without member variables occupy space?
问题描述
我发现MSVC和GCC编译器为每个类实例分配至少一个字节,即使该类是没有成员变量(或只有静态成员变量)的谓词。以下代码说明了这一点。
I found that both MSVC and GCC compilers allocate at least one byte per each class instance even if the class is a predicate with no member variables (or with just static member variables). The following code illustrates the point.
#include <iostream>
class A
{
public:
bool operator()(int x) const
{
return x>0;
}
};
class B
{
public:
static int v;
static bool check(int x)
{
return x>0;
}
};
int B::v = 0;
void test()
{
A a;
B b;
std::cout << "sizeof(A)=" << sizeof(A) << "\n"
<< "sizeof(a)=" << sizeof(a) << "\n"
<< "sizeof(B)=" << sizeof(B) << "\n"
<< "sizeof(b)=" << sizeof(b) << "\n";
}
int main()
{
test();
return 0;
}
输出:
sizeof(A)=1
sizeof(a)=1
sizeof(B)=1
sizeof(b)=1
我的问题是为什么编译器需要它?我可以想出的唯一原因是确保所有成员var指针不同,所以我们可以通过比较指针来区分类型A或B的两个成员。但是当处理小型容器时,这种方法的成本相当严格。考虑到可能的数据对齐,我们可以得到高达16字节每个类没有vars(?!)。假设我们有一个自定义容器,通常保存几个int值。然后考虑这样的容器的数组(有大约1000000成员)。开销将是16 * 1000000!可能发生的一个典型情况是具有存储在成员变量中的比较谓词的容器类。另外,考虑到类实例应该总是占用一些空间,当调用A()(value)时,应该预期什么类型的开销?
My question is why does compiler need it? The only reason that I can come up with is ensure that all member var pointers differ so we can distinguish between two members of type A or B by comparing pointers to them. But the cost of this is quite severe when dealing with small-size containers. Considering possible data alignment, we can get up to 16 bytes per class without vars (?!). Suppose we have a custom container that will typically hold a few int values. Then consider an array of such containers (with about 1000000 members). The overhead will be 16*1000000! A typical case where it can happen is a container class with a comparison predicate stored in a member variable. Also, considering that a class instance should always occupy some space, what type of overhead should be expected when calling A()(value) ?
推荐答案
必须满足来自C ++标准的不变量:同一类型的每个C ++对象都需要有一个唯一的可识别的地址。
It’s necessary to satisfy an invariant from the C++ standard: every C++ object of the same type needs to have a unique address to be identifiable.
没有空格,则数组中的项将共享相同的地址。
If objects took up no space, then items in an array would share the same address.
这篇关于为什么没有成员变量的C ++类占用空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!