Cpp 对象模型探索 / 含有虚基类的类的内存布局
一、栗子
class Grand
{
public:int i_grand_ = 8;
};class Parent1 : public virtual Grand
{
public:int i_parent1_ = 9;
};class Parent2 : public virtual Grand
{
public:int i_parent2_ = 10;
};class Son : public Parent1,public Parent2
{
public:int i_son_ = 11;
};int main()
{return 0;
}
打开 Developer Command Prompt for VS 2019 ,当前目录切换到该工程所在目录,执行如下指令:
cl /d1 reportSingleClassLayoutParent1 test1.cpp1、cl "l"是小写的“L”。
2、d1 “1”是数字“1”。
3、“reportSingleClassLayoutParent1” 是 “reportSingleClassLayout” + 类名,即:要查看数据结构的/类的名字。
4、"test1.cpp",该类所在的代码文件。
二、Parent 类的内存布局
执行指令
cl /d1 reportSingleClassLayoutParent1 test1.cpp
得到如下图所示的结果

根据上图得到下图所示的 Parent1 类的内存布局。

三、Son 类的内存布局
执行指令
cl /d1 reportSingleClassLayoutSon test1.cpp
得到如下图所示的结

根据上图得到下图所示的 Son 类的内存布局。

四、总结
- 若 Grand 类为虚基类,则 Parent 类和 Son 类的内存布局中,该虚基类会排布在该类的最下面。
- 若父类是虚基类,则子类会生成 vbptr,该指针指向 vbtable 。后序会讲解。
- 对于 Son 类来说,因为其并没有虚继承父类,故其本身没有 vbptr 。
五、其他
- vbtable,英文全称:virtual base table,中文名称:虚函数表。
- vbptr,英文全称:vritual base table pointer,中文名称:虚函数表指针。
(SAW:Game Over!)
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
