具有虚函数的类的大小增加了额外的 4 个字节

2022-01-24 00:00:00 polymorphism c++
    class NoVirtual {
        int a;
    public:
        void x() const {}
        int i() const { return 1; }
    };

    class OneVirtual {
        int a;
    public:
        virtual void x() const {}
        int i() const { return 1; }
    };

    class TwoVirtuals {
        int a;
    public:
        virtual void x() const {}
        virtual int i() const { return 1; }
    };

    int main() {
        cout << "int: " << sizeof(int) << endl;
        cout << "NoVirtual: "
             << sizeof(NoVirtual) << endl;
        cout << "void* : " << sizeof(void*) << endl;
  cout << "OneVirtual: "
       << sizeof(OneVirtual) << endl;
  cout << "TwoVirtuals: "
       << sizeof(TwoVirtuals) << endl;

    return 0;
}

输出为:

非虚拟:4
无效*:8
OneVirtual:16
两个虚拟:16

NoVirtual: 4
void* : 8
OneVirtual: 16
TwoVirtuals: 16

问题是:

由于 OneVirtual 和 TwoVirtuals 类具有虚函数,类的大小应为 sizeof(int) + sizeof(void*) 即 12 字节.但大小打印为 16 字节.

Since OneVirtual and TwoVirtuals class have virtual function, size of class should be sizeof(int) + sizeof(void*) i.e. 12bytes. But size is printed as 16bytes.

谁能解释一下原因?

推荐答案

我假设你是在 64 位机器上编译,因为 int 的大小是 4 字节.对于 64 位机器,指针大小通常是 8 字节,int 大小是 4 字节.满足 数据对齐要求 以节省读取周期编译器添加了额外的 4 个字节(填充),因此结果是 16 个字节,而实际需要的大小是 12 个字节.

I assume you are compiling on 64bit machines since size of int is 4bytes.Typically for 64bit machines pointer size will be 8 bytes and int size is 4 bytes.To satisfy Data Alignment requirement to save read cycles compiler adds extra 4 bytes(padding) hence result is 16bytes where as actual required size is 12 bytes.

相关文章