具有虚拟功能的类的大小

Size of class with virtual function

本文关键字:功能 虚拟      更新时间:2023-10-16

我正在修改C++概念,但我被困在一个非常简单的代码中

#include <iostream>
using namespace std;
class foo {
public:
    //int i;
    void virtual foobar()
    {
        cout << "foobarn";
    }
};
int main()
{
    foo f;
    cout << sizeof(f) << endl;
    //cout << sizeof(f.i) << endl;
    return 1;
}

上述代码的输出为 8但是当我从代码中删除注释时输出为 16 和 4

我不明白当类不存在成员变量时,VPTR 大小为 8,但在添加变量大小后变为 12。

您正在使用指针对齐到 8 个字节的平台。由于虚拟表指针通常是对象布局中的第一件事,因此它也必须与 8 个字节对齐。因此,在 int 成员之后插入填充 4 个字节,这就是为什么您的大小为 16(vf 表指针为 8 个字节,int 为 4 个字节,4 个填充字节)。