首页 > 系统相关 >C++内存模型实践探索

C++内存模型实践探索

时间:2024-10-18 23:35:09浏览次数:1  
标签:... Derive 探索 virtual int C++ single Base 内存

前言

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

虚函数表简介

虚函数表布局

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

// Derive.h
class Base_C
{
public:
    Base_C();
    virtual ~Base_C();

private:
    int baseC;
};

// Derive.cc
Base_C::Base_C()
{
}

Base_C::~Base_C()
{
}

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

// g++ -O0 -std=c++11 -fdump-class-hierarchy Derive.h
Vtable for Base_C
Base_C::_ZTV6Base_C: 4u entries
0     (int (*)(...))0
8     (int (*)(...))(& _ZTI6Base_C)
16    (int (*)(...))Base_C::~Base_C
24    (int (*)(...))Base_C::~Base_C

Class Base_C
   size=16 align=8
   base size=12 base align=8
Base_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的内存布局如下图所示:
Base_C Object Layout

 

继承下的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_single
Derive_single::_ZTV13Derive_single: 7u entries
0     (int (*)(...))0
8     (int (*)(...))(& _ZTI13Derive_single)
16    (int (*)(...))Derive_single::~Derive_single
24    (int (*)(...))Derive_single::~Derive_single
32    (int (*)(...))Base_D::add
40    (int (*)(...))Derive_single::print
48    (int (*)(...))Derive_single::Derive_single_print

Class Derive_single
   size=24 align=8
   base size=20 base align=8
Derive_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)

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

多继承下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_multiBase
Derive_multiBase::_ZTV16Derive_multiBase: 13u entries
0     (int (*)(...))0
8     (int (*)(...))(& _ZTI16Derive_multiBase)
16    (int (*)(...))Derive_multiBase::~Derive_multiBase
24    (int (*)(...))Derive_multiBase::~Derive_multiBase
32    (int (*)(...))Derive_multiBase::print
40    (int (*)(...))Derive_multiBase::add
48    (int (*)(...))Derive_multiBase::Derive_multiBase_print
56    (int (*)(...))-16
64    (int (*)(...))(& _ZTI16Derive_multiBase)
72    (int (*)(...))Derive_multiBase::_ZThn16_N16Derive_multiBaseD1Ev
80    (int (*)(...))Derive_multiBase::_ZThn16_N16Derive_multiBaseD0Ev
88    (int (*)(...))Derive_multiBase::_ZThn16_N16Derive_multiBase3addEv
96    (int (*)(...))Derive_multiBase::_ZThn16_N16Derive_multiBase5printEv

Class Derive_multiBase
   size=32 align=8
   base size=32 base align=8
Derive_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
A segment of code associated (in this ABI) with a target function, 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.

内存布局如下图所示:
Multi Derive Object Layout

 

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

enable_shared_from_this文档中有如下描述:

A common implementation for enable_shared_from_this is to hold a weak reference (such as std::weak_ptr) to *this. 
For the purpose of exposition, the weak reference is called weak-this and considered as a mutable std::weak_ptr member.

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_single
Derive_single::_ZTV13Derive_single: 7u entries
0     (int (*)(...))0
8     (int (*)(...))(& _ZTI13Derive_single)
16    (int (*)(...))Derive_single::~Derive_single
24    (int (*)(...))Derive_single::~Derive_single
32    (int (*)(...))Base_D::add
40    (int (*)(...))Derive_single::print
48    (int (*)(...))Derive_single::Derive_single_print

Class Derive_single
   size=40 align=8
   base size=36 base align=8
Derive_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_ptr
Like 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特性不影响虚函数表的内容

 

 

参考资料

Itanium C++ ABI
图说C++对象模型:对象内存布局详解
C++对象模型
C++深入探索C++多态②-继承关系
虚函数继承-thunk技术初探
C++:虚函数内存布局解析(以clang编译器为例)

   

标签:...,Derive,探索,virtual,int,C++,single,Base,内存
From: https://www.cnblogs.com/hueyxu/p/18475198

相关文章

  • C++ WM\_COPYDATA 实现进程通信
    基于MFC用于存储数据的自定义结构体:structMSG_STRUCT{ wchar_tmsg[256];};发送端,发送按钮响应事件的代码voidCSendWM_COPYDATADlg::OnBnClickedSendmessage(){ MSG_STRUCTsmsg; GetDlgItemText(IDC_MESSAGE,smsg.msg,256); HWNDhTargetWnd=NULL; hTargetWnd=::Fi......
  • C++使用共享内存实现进程间通信
    C++使用共享内存实现进程间通信文件映射是一种实现进程间单向或双向通信的机制。它允许两个或多个本地进程间相互通信。为了共享文件或内存,所有的进程必须使用相同的文件映射的名字或是句柄。为了实现共享文件,第一个进程先调用CreateFile方法。接下来调用CreateFileMappin......
  • 算法笔记 C/C++快速入门 | 全章节整理
    目录零.【C语言中的输入和输出函数】sscanf应用场景1:解析用户输入应用场景2:解析文件内容应用场景3:处理网络协议数据应用场景4:字符串解析和数据转换应用场景5:解析复杂的日志数据其他应用场景:scanf 一【编程语言相关】c和cpp二.【数据结构相关】结构体循环定......
  • C++之类和对象2
    文章目录1.类的默认成员函数有哪些2.构造函数3.析构函数4.拷贝构造函数5.赋值运算符重载函数5.1运算符重载5.2赋值运算符重载函数6.取地址运算符重载函数6.1const成员函数6.2普通取地址重载函数与const取地址运算符重载函数1.类的默认成员函数有哪些默认构造函数是......
  • 【C++】string类(1)
    ......
  • 【GESP】C++一级练习BCQM3048,顺序执行、逆推运算
    一道根据结果,一步一步逆推之前结果的题,完全顺序语句执行题目题解详见:https://www.coderli.com/gesp-1-bcqm3048/【GESP】C++一级练习BCQM3048,顺序执行、逆推运算|OneCoder一道根据结果,一步一步逆推之前结果的题,完全顺序语句执行。https://www.coderli.com/gesp-1-bcqm3048/......
  • 【GESP】C++一级练习BCQM3049,细胞分裂
    GESP一级知识点整形int和for循环练习。题目题解详见:【GESP】C++一级练习BCQM3049,细胞分裂|OneCoder【GESP】C++一级练习BCQM3049,细胞分裂|OneCoderGESP一级知识点整形int和for循环练习。https://www.coderli.com/gesp-1-bcqm3049/C++GESP专项交流频道:GESP学习交流频道......
  • 【信奥赛·C++基础语法】CSP-J C++ 指针与引用
    序言指针和引用是非常重要的概念,它们提供了对内存的直接访问和操作方式,使得程序员能够更加灵活地处理数据哈,理解指针和引用的工作原理以及正确使用它们,对于编写高效、安全的C++程序至关重要。一、指针的基本概念指针的定义和作用指针是一个变量,它存储了另一个变量的内......
  • QT/c++相关记录
     QT的大部分容器类(如QString、QVector等)都是使用隐式共享(implicitsharing)技术,这是通过写时复制(copy-on-write,COW)实现的优化模式。理解这一点的关键在于,Qt的容器类需要在对象拷贝时高效处理数据,而隐式共享则允许在栈上操作容器的同时,在需要时共享内部数据的堆上存储。......
  • 必学的简单排序算法——选择排序(c++)
    标题前言一、什么是选择排序二、算法图解三、经典例题1、颜色分类题解思路代码题解2、至少是其他数字两倍的最大数解题思路代码题解3、寻找两个正序数组的中位数解题思路代码题解前言排序算法虽然简单,但是我也要掌握熟练应用,因为学习算法这个复杂的过程,我们应该......