C++ 对象模型
nxdong July 23, 2022 [c++] #c++c++对象模型.
C++ 对象模型
通过两个步骤实现C++对象模型:
- A table of pointers to virtual functions is generated for each class (this is called the virtual table). 为每一个类生成一个由指向虚函数的指针们组成的虚函数表.
- A single pointer to the associated virtual table is inserted within each class object (traditionally, this has been called the vptr). The setting, resetting, and not setting of the vptr is handled automatically through code generated within each class constructor, destructor, and copy assignment operator. The type_info object associated with each class in support of runtime type identification (RTTI) is also addressed within the virtual table, usually within the table’s first slot. 一个指向虚函数表的指针会被插入到每一个类对象(一般管这个叫vptr). vptr的setting,resetting或者不设置由每个类的构造函数,析构函数,和拷贝赋值操作生成的代码自动处理. 每个类的type_info 对象(为了支持RTTI)也放在虚函数表里,一般放在第一个槽里.
RTTI
它允许检索对象类型信息(使用typeid运算符)以及在运行时检查继承层次结构(使用dynamic_cast)。RTTI仅在存在多态性行为时可用,即类至少有一个虚拟函数。
https://alex-robenko.gitbook.io/bare_metal_cpp/compiler_output/rtti
https://www.geeksforgeeks.org/rtti-run-time-type-information-in-cpp/
clang 对象结构打印
基本类继承
base.cpp 内容如下:
;
;
;
int
命令行输出对象结构:
|
|
| [sizeof=4, dsize=4, align=4,
| nvsize=4, nvalign=4]
|
|
|
| [sizeof=16, dsize=16, align=8,
| nvsize=16, nvalign=8]
|
| )
|
|
|
|
|
|
|
| [sizeof=40, dsize=33, align=8,
| nvsize=33, nvalign=8]
带虚函数的继承
vtable.cpp 文件内容如下:
;
;
;
int
命令行执行(注意命令行参数的变化):
|
| ()
|
| [sizeof=16, dsize=12, align=8,
| nvsize=12, nvalign=8]
|
|
|
| [sizeof=16, dsize=16, align=8,
| nvsize=16, nvalign=8]
|
| )
| ()
|
|
|
|
|
|
|
| [sizeof=48, dsize=41, align=8,
| nvsize=41, nvalign=8]
)
| )
|
)
|
)
|
)
| )
|
)
)
|
)
|
备注
gcc打印虚表:
参考资料
https://alex-robenko.gitbook.io/bare_metal_cpp/compiler_output/rtti
https://www.geeksforgeeks.org/rtti-run-time-type-information-in-cpp/
https://eli.thegreenplace.net/2012/12/17/dumping-a-c-objects-memory-layout-with-clang/