类方法是否会增加类实例的大小? [英] Do class methods increase the size of the class instances?

查看:127
本文介绍了类方法是否会增加类实例的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题很简单。为了清楚起见,考虑下面的例子:

The question is pretty straight forward. For clarity, consider the example below:

// 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;
}

做实例 f b d1 d2 内存中的空间量?作为这个问题的扩展,当传递 Foo 的实例需要比 Bar 更长的时间,理论上

Do instances f, b, d1, and d2 all occupy the same amount of space in memory? As an extension to this question, would copying instances of Foo when passing it around take longer than Bar, theoretically?

推荐答案

只有实例数据增加了一个类的实例(在我知道的所有实现中)的大小,虚函数或继承自具有虚函数的类,然后你对v表指针进行一次性命中。

Only instance data increases the size of instances of a class (in all implementations that I know of), except that if you add virtual functions or inherit from a class with virtual functions then you take a one-time hit for a v-table pointer.

此外,由于别人正确地提到最小大小

Also, as someone else correctly mentions the minimum size of a class is 1 byte.

一些示例:

// 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表指针或其他方法处理多个虚拟继承,将对类大小产生影响。

Compiler implementations may handle multiple virtual inheritance with multiple v-table pointers or other other methods, so these too will have effect on the class size.

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

Finally, member data alignment options can have an impact. The compiler may have some option or #pragma to specify that member data should have a starting address that is a multiple of the number of bytes specified. For example, with alignment on 4 byte boundaries and assuming 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;
};

这篇关于类方法是否会增加类实例的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆