C++ 多态内存成本

标签 c++ polymorphism virtual-functions

我有这段代码:

    #include <stdio.h>

    class CoolClass {
    public:
      virtual void set(int x){x_ = x;};
      virtual int get(){return x_;};
    private:
      int x_;
    };

    class PlainOldClass {
    public:
      void set(int x) {x_ = x;};
      int get(){return x_;}
    private:
      int x_;
    };
    int main(void) {
      printf("CoolClass size: %ld\n", sizeof(CoolClass));
      printf("PlainOldClass size: %ld\n", sizeof(PlainOldClass));
      return 0;
    }

我有点困惑,因为它说 CoolClass 的大小是 16?如何?为什么?即使有指向 vtable 的指针,大小不应该是 8 吗? oldclass 的大小如预期的那样是 4。

编辑:我正在使用 g++ 4.6.3 运行 Linux Mint 64 位。

最佳答案

除了 charunsigned char 之外,您不能假设任何其他内容的大小。如果您在 64 位平台上构建,int 可能仍然是 4 个字节,但虚拟表指针的大小可能是 8,额外的 4 个字节用于填充(以便指针对齐到 8 个字节)。

64 位

+----+----+----+----+
| vp | vp | x_ | p  |
+----+----+----+----+

vp - virtual table pointer
x_ - member
p  - padding byte

32 位

+----+----+
| vp | x_ |
+----+----+

vp - virtual table pointer
x_ - member
p  - padding byte

Padding not required because the pointer is already aligned

作为测试,你可以试试

class PlainOldClass {
private:
  int* x_;
};

它的大小为 8。

关于C++ 多态内存成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15742337/

相关文章:

c# - 计算闪存驱动器内容的校验和

c++ - error : no match for 'operator=' . 尝试从基类继承并从基类初始化?

c++ - 有没有办法将抽象对象转换给它的 child ?

c++ - 为什么要在 C++ 中使用虚函数?

java - 关于java虚方法的问题

c++ - 派生纯虚函数的实现

C++ vector 元素删除与新 vector 创建

c++ - Hinnant 的 short_alloc 只在栈上

c++ - 没有默认构造函数的静态 C++ 变量丢失值

c++ - 使用非虚覆盖隐藏虚函数