写点什么

C++ 对象模型实践探索

  • 2024-12-05
    福建
  • 本文字数:5422 字

    阅读完需:约 18 分钟

前言


C++对象模型是个常见、且复杂的话题,本文基于 Itanium C++ ABI 通过程序实践介绍了几种 简单 C++继承 场景下对象模型,尤其是存在虚函数的场景,并通过图的方式直观表达内存布局。本文展示的程序构建环境为 Ubuntu,glibc 2.24,gcc 6.3.0。由于 clang 和 gcc 编译器都是基于 Itanium C++ ABI,因此本文介绍的对象模型对 clang 编译的程序也基本适用。


虚函数表简介


虚函数表布局


含有虚函数的类,编译器会为其添加一个虚函数表(vptr)。用如下程序验证含有虚函数的类的内存布局,该程序很简单,只定义了构造函数,虚析构函数,和一个 int 成员变量。


// Derive.hclass Base_C{public:    Base_C();    virtual ~Base_C();
private: int baseC;};
// Derive.ccBase_C::Base_C(){}
Base_C::~Base_C(){}
复制代码


gcc 编译器可通过-fdump-class-hierarchy参数,查看类的内存布局。可得到如下信息:


// g++ -O0 -std=c++11 -fdump-class-hierarchy Derive.hVtable for Base_CBase_C::_ZTV6Base_C: 4u entries0     (int (*)(...))08     (int (*)(...))(& _ZTI6Base_C)16    (int (*)(...))Base_C::~Base_C24    (int (*)(...))Base_C::~Base_C
Class Base_C size=16 align=8 base size=12 base align=8Base_C (0x0x7fb8e9185660) 0 vptr=((& Base_C::_ZTV6Base_C) + 16u)
复制代码


从类Base_C的定义来看,类占用的空间包括一个虚函数表指针 vptr 和一个整型变量。由于内存对齐的原因,类占用 16 字节。接下来看虚函数表,表中一共有 4 个 entry,每个 entry 都是函数指针,指向具体的虚函数,因此每个 entry 在测试的机器上编译占 8 字节(指针大小)。


注意看到表中虚析构函数有两个,这实际上是 Itanium C++ ABI 规定的:


The entries for virtual destructors are actually pairs of entries. The first destructor, called the complete object destructor, performs the destruction without calling delete() on the object. The second destructor, called the deleting destructor, calls delete() after destroying the object. Both destroy any virtual bases; a separate, non-virtual function, called the base object destructor, performs destruction of the object but not its virtual base subobjects, and does not call delete().
复制代码


虚析构函数在虚函数表中占用两条目,分别是complete object destructordeleting destructor


除了析构函数,虚函数表还有两个条目,紧靠析构函数的是typeinfo指针,指向类型信息对象(typeinfo object),用于运行时类型识别(RTTI)。


第一个条目看起来可能比较陌生,是offset,该偏移存储了从当前虚表指针(vtable pointer)位置到对象顶部的位移。在 ABI 文档中这两个条目均有详细的介绍:


// typeinfo指针The typeinfo pointer points to the typeinfo object used for RTTI. It is always present. All entries in each of the virtual tables for a given class must point to the same typeinfo object.A correct implementation of typeinfo equality is to check pointer equality, except for pointers (directly or indirectly) to incomplete types. The typeinfo pointer is a valid pointer for polymorphic classes, i.e. those with virtual functions, and is zero for non-polymorphic classes.
复制代码


// offset偏移The offset to top holds the displacement to the top of the object from the location within the object of the virtual table pointer that addresses this virtual table, as a ptrdiff_t. It is always present. The offset provides a way to find the top of the object from any base subobject with a virtual table pointer. This is necessary for dynamic_cast<void*> in particular. In a complete object virtual table, and therefore in all of its primary base virtual tables, the value of this offset will be zero. For the secondary virtual tables of other non-virtual bases, and of many virtual bases, it will be negative. Only in some construction virtual tables will some virtual base virtual tables have positive offsets, due to a different ordering of the virtual bases in the full object than in the subobject's standalone layout.
复制代码


另外需要注意的是:vptr=((& Base_C::_ZTV6Base_C) + 16u),虽然虚函数表中有四个条目,但是 vptr 的指针实际上并不是指向表的起始位置,而是指向第一个虚函数的位置


Base_C的内存布局如下图所示:



继承下的 C++对象模型


单继承下 C++对象模型


首先,看一个单继承场景的例子:


// 此处省略类的实现部分class Base_C{public:    Base_C();    virtual ~Base_C();
private: int baseC;};
class Base_D : public Base_C{public: Base_D(int i); virtual ~Base_D(); virtual void add(void) { cout << "Base_D::add()..." << endl; } virtual void print(void);
private: int baseD;};
class Derive_single : public Base_D{public: Derive_single(int d); void print(void) override; virtual void Derive_single_print();
private: int Derive_singleValue;};
复制代码


单继承场景下,派生类有且只有一个虚表(将基类的虚表复制),同时派生类中 override 的虚函数,会在虚函数表中对原函数进行覆盖派生类新增的虚函数也将追加到虚函数表的尾部。从整体内存布局上来看,派生类中新增的非静态成员变量,也会追加到基类的成员变量之后。打印类内存布局如下:


Vtable for Derive_singleDerive_single::_ZTV13Derive_single: 7u entries0     (int (*)(...))08     (int (*)(...))(& _ZTI13Derive_single)16    (int (*)(...))Derive_single::~Derive_single24    (int (*)(...))Derive_single::~Derive_single32    (int (*)(...))Base_D::add40    (int (*)(...))Derive_single::print48    (int (*)(...))Derive_single::Derive_single_print
Class Derive_single size=24 align=8 base size=20 base align=8Derive_single (0x0x7fb8e93fe8f0) 0 vptr=((& Derive_single::_ZTV13Derive_single) + 16u) Base_D (0x0x7fb8e93fe958) 0 primary-for Derive_single (0x0x7fb8e93fe8f0) Base_C (0x0x7fb8e91857e0) 0 primary-for Base_D (0x0x7fb8e93fe958)
复制代码


内存布局如下图所示,内存布局和上述描述一致:



多继承下 C++对象模型(非菱形)


接下来考虑非菱形多继承场景,此时对于派生类,会将其每个基类的虚函数表“拷贝”一份,最终组成虚函数表组,虚函数表排列顺序,由基类在类定义中的声明顺序决定。派生类的虚函数被放在声明的第一个基类的虚函数表中,派生类对基类函数 override 时,会覆盖所有基类中对应的函数。


// 此处省略类的实现部分class Base_A{public:    Base_A(int i);    virtual ~Base_A();    int getValue();    static void countA();    virtual void print(void);
private: int baseA; static int baseAS;};
class Base_B{public: Base_B(int i); virtual ~Base_B(); int getValue(); virtual void add(void); static void countB(); virtual void print(void);
private: int baseB; static int baseBS;};
class Derive_multiBase : public Base_A, public Base_B{public: Derive_multiBase(int d); void add(void) override; void print(void) override; virtual void Derive_multiBase_print();
private: int Derive_multiBaseValue;};
复制代码


打印类内存布局如下:


Vtable for Derive_multiBaseDerive_multiBase::_ZTV16Derive_multiBase: 13u entries0     (int (*)(...))08     (int (*)(...))(& _ZTI16Derive_multiBase)16    (int (*)(...))Derive_multiBase::~Derive_multiBase24    (int (*)(...))Derive_multiBase::~Derive_multiBase32    (int (*)(...))Derive_multiBase::print40    (int (*)(...))Derive_multiBase::add48    (int (*)(...))Derive_multiBase::Derive_multiBase_print56    (int (*)(...))-1664    (int (*)(...))(& _ZTI16Derive_multiBase)72    (int (*)(...))Derive_multiBase::_ZThn16_N16Derive_multiBaseD1Ev80    (int (*)(...))Derive_multiBase::_ZThn16_N16Derive_multiBaseD0Ev88    (int (*)(...))Derive_multiBase::_ZThn16_N16Derive_multiBase3addEv96    (int (*)(...))Derive_multiBase::_ZThn16_N16Derive_multiBase5printEv
Class Derive_multiBase size=32 align=8 base size=32 base align=8Derive_multiBase (0x0x7fb8e910cd20) 0 vptr=((& Derive_multiBase::_ZTV16Derive_multiBase) + 16u) Base_A (0x0x7fb8e91855a0) 0 primary-for Derive_multiBase (0x0x7fb8e910cd20) Base_B (0x0x7fb8e9185600) 16 vptr=((& Derive_multiBase::_ZTV16Derive_multiBase) + 72u)
复制代码


从内存布局中可看到存在两个 vptr(分别指向两个虚函数表),对应Derive_multiBase从两个基类Base_ABase_B拷贝得到的虚函数表。派生类Derive_multiBase中所有虚函数都拓展在主虚函数表(primary virtual table),也即从Base_A拷贝得到的虚函数表。从Base_B拷贝得到的虚函数表也称为辅助虚函数表(secondary virtual tables),从内存布局中看到其offset-16,因为此虚函数表指针距对象内存的初始位置 16 个字节。


同时注意到此虚函数表中虚函数符号为non-virtual thunk to...,这个和函数跳转的机制有关,通过 thunk 对调用不同父类的函数的地址进行修正,可以参考深入探索 C++多态②-继承关系、C++对象模型中的介绍。


// thunk<strong>A segment of code associated (in this ABI) with a target function</strong>, which is called instead of the target function for the purpose of modifying parameters (e.g. this) or other parts of the environment before transferring control to the target function, and possibly making further modifications after its return. A thunk may contain as little as an instruction to be executed prior to falling through to an immediately following target function, or it may be a full function with its own stack frame that does a full call to the target function.
复制代码


内存布局如下图所示:



讨论:enable_shared_from_this 特性如何影响内存布局


enable_shared_from_this文档中有如下描述:


A common implementationfor

 enable_shared_from_this is to <strong>hold a weak reference (such as std::weak_ptr) to *this</strong>.

For the purpose of exposition, the weak reference is called weak-this

 and considered as <strong>amutable std::weak_ptr member</strong>.


enable_shared_from_this 的通常实现是让实例拥有一个“弱引用”,可表现为实例有个 std::weak_ptr 的成员变量。可在单继承场景的测试代码上进行验证,对Derive_single类增加继承自std::enable_shared_from_this<Derive_single>,其他不变:


class Derive_single : public Base_D, public std::enable_shared_from_this<Derive_single>{public:    Derive_single(int d);    void print(void) override;    virtual void Derive_single_print();
private: int Derive_singleValue;};
复制代码


首先打印类内存布局如下:


Vtable for Derive_singleDerive_single::_ZTV13Derive_single: 7u entries0     (int (*)(...))08     (int (*)(...))(& _ZTI13Derive_single)16    (int (*)(...))Derive_single::~Derive_single24    (int (*)(...))Derive_single::~Derive_single32    (int (*)(...))Base_D::add40    (int (*)(...))Derive_single::print48    (int (*)(...))Derive_single::Derive_single_print
Class Derive_single size=40 align=8 base size=36 base align=8Derive_single (0x0x7fd5c76431c0) 0 vptr=((& Derive_single::_ZTV13Derive_single) + 16u) Base_D (0x0x7fd5c7639750) 0 primary-for Derive_single (0x0x7fd5c76431c0) Base_C (0x0x7fd5c7632780) 0 primary-for Base_D (0x0x7fd5c7639750) std::enable_shared_from_this<Derive_single> (0x0x7fd5c76327e0) 16
复制代码


对比前文,可发现Derive_single内存占用由 24 字节增大到 40 字节,原因是std::enable_shared_from_this<Derive_single>的继承多占用了 16 字节。从 std::weak_ptr 的文档中可知std::weak_ptr的典型实现实际上是存储了两个指针,和这里的 16 字节内存增长一致。


// std::weak_ptrLike std::shared_ptr, a typical implementation of weak_ptr stores two pointers:-- a pointer to the control block; -- the stored pointer of the shared_ptr it was constructed from.
复制代码


另外,特别注意此时Derive_single类虚函数表和前文没有差异,因此 enable_shared_from_this 特性不影响虚函数表的内容


文章转载自:huey_x

原文链接:https://www.cnblogs.com/hueyxu/p/18475198

体验地址:http://www.jnpfsoft.com/?from=infoq

用户头像

还未添加个人签名 2023-06-19 加入

还未添加个人简介

评论

发布
暂无评论
C++对象模型实践探索_c++_快乐非自愿限量之名_InfoQ写作社区