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

标签 c++ class memory-management methods

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

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

相关文章:

c++11 chrono 未引用的局部变量

c++ - std::scoped_lock 或 std::unique_lock 或 std::lock_guard?

java - 在类中设置值不起作用

iphone - 应用程序终止时,系统是否释放我的对象?

c++ - 这个类的构造函数/析构函数有问题吗?

c++ - 是否有 C++/Win32/MFC(如 Sparkle)的自动更新框架?

java - 在我的任务中创建方法时出现问题

c++ - 派生类使用基类中的重载运算符时出错

ios - 将 userLocation 打印到 textLabel

memory-management - 4GB 进程如何在仅 2GB RAM 上运行?