gpt4 book ai didi

c++ - 类方法会增加类实例的大小吗?

转载 作者:IT老高 更新时间:2023-10-28 12:48:04 26 4
gpt4 key购买 nike

这个问题很简单。为清楚起见,请考虑以下示例:

// Note that none of the class have any data members
// Or if they do have data members, they're of equal size, type, and quantity
class Foo {
public:
void foo1();
void foo2();
// 96 other methods ...
void foo99();
};

class Bar {
public:
// Only one method
void bar();
};

class Derived1 : public Foo { };
class Derived2 : public Bar { };

int main() {
Foo f;
Bar b;
Derived1 d1;
Derived2 d2;
return 0;
}

Do 实例 fbd1d2 都占用相同数量的内存空间?作为这个问题的扩展,理论上复制 Foo 的实例会比 Bar 花费更长的时间吗?

最佳答案

只有实例数据会增加类实例的大小(在我所知道的所有实现中),除了如果你添加虚函数或从具有虚函数的类继承,那么你会一次性命中 v - 表指针。

另外,正如其他人正确提到的那样,一个类的最小大小是 1 个字节。

一些例子:

// size 1 byte (at least)
class cls1
{
};

// size 1 byte (at least)
class cls2
{
// no hit to the instance size, the function address is used directly by calling code.
int instanceFunc();
};

// sizeof(void*) (at least, for the v-table)
class cls3
{
// These functions are indirectly called via the v-table, a pointer to which must be stored in each instance.
virtual int vFunc1();
// ...
virtual int vFunc99();
};

// sizeof(int) (minimum, but typical)
class cls4
{
int data;
};

// sizeof(void*) for the v-table (typical) since the base class has virtual members.
class cls5 : public cls3
{
};

编译器实现可以使用多个 v-table 指针或其他方法处理多个虚拟继承,因此这些也会影响类大小。

最后,成员数据对齐选项可能会产生影响。编译器可能有一些选项或 #pragma 来指定成员数据的起始地址应该是指定字节数的倍数。例如,在 4 字节边界上对齐并假设 sizeof(int) = 4:

// 12 bytes since the offset of c must be at least 4 bytes from the offset of b. (assuming sizeof(int) = 4, sizeof(bool) = 1)
class cls6
{
int a;
bool b;
int c;
};

关于c++ - 类方法会增加类实例的大小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8058213/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com