C++多态内存成本

dar*_*sys 5 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;
    }
Run Code Online (Sandbox Code Playgroud)

我有点困惑,因为它说CoolClass的大小是16?怎么样?为什么?即使使用指向vtable的指针,大小也不应该是8?旧类的大小是预期的4.

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

Luc*_*ore 5

你不能假设除了char或之外的任何东西的大小unsigned char.如果你在64位平台上构建,int可能仍然是4个字节,但虚拟表指针的大小可能是8,并且额外的4个字节用于填充(以便指针对齐到8个字节).

64位

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

vp - virtual table pointer
x_ - member
p  - padding byte
Run Code Online (Sandbox Code Playgroud)

32位

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

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

Padding not required because the pointer is already aligned
Run Code Online (Sandbox Code Playgroud)

作为测试,你可以试试

class PlainOldClass {
private:
  int* x_;
};
Run Code Online (Sandbox Code Playgroud)

它的大小是8.