带有虚函数的类的大小 [英] Size of class with virtual function
问题描述
我修改了C ++的概念,但是我遇到了一个非常简单的代码。
I was revising the C++ concepts, but I am stuck with a very simple code
#include <iostream>
using namespace std;
class foo {
public:
//int i;
void virtual foobar()
{
cout << "foobar\n";
}
};
int main()
{
foo f;
cout << sizeof(f) << endl;
//cout << sizeof(f.i) << endl;
return 1;
}
上述代码的输出是8
但是当我删除代码中的注释
输出是16和4
The output of the above code is 8 But when I removed comments from the code Output is 16 and 4
我不明白当类没有成员变量存在,然后VPTR大小是8,但添加一个变量size = 12。
I did not understand when the class have no member variable present then VPTR size is 8 but after adding a variable size becomes 12.
推荐答案
您正在使用一个指针与8个字节对齐的平台。由于虚拟表指针通常是对象布局中的第一件事,它也必须对齐到8个字节。因此,在 int
成员之后插入填充4个字节,这就是为什么你获得大小为16(vf表指针为8字节,int和4填充字节为4) 。
You're working on a platform where pointers are aligned to 8 bytes. Since the virtual table pointer is typically the first thing in the layout of an object, it too must be aligned to 8 bytes. So padding 4 bytes are inserted after the int
member, that's why you get a size of 16 (8 bytes for the vf table pointer, 4 for the int and 4 padding bytes).
这篇关于带有虚函数的类的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!