Discuz! Board

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1388|回复: 0
打印 上一主题 下一主题

C++虚表,你搞懂了吗?

[复制链接]

388

主题

602

帖子

2218

积分

金牌会员

Rank: 6Rank: 6

积分
2218
跳转到指定楼层
楼主
发表于 2016-7-3 10:13:15 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 hechengjin 于 2016-7-3 10:43 编辑

http://blog.jobbole.com/103102/

前言

我们说的虚表其实有很多种叫法:

  • virtual method table(VMT)
  • virtual function table(vftable)
  • virtual call table
  • dispatch table
  • vtable

这些都是虚表的意思。虚表是一种利用程序语言实现的dynamic dispatch机制,或者说runtime method binding机制,也就是我们说的多态。

注:笔者在本文使用C++语言,并且统一用vTable来表示虚表。

虚函数

用virtual关键字修饰的函数就叫虚函数

因为vTable(虚表)是C++利用runtime来实现多态的工具,所以我们需要借助virtual关键字将函数代码地址存入vTable来躲开静态编译期。这里我们先不深入探究,后面我会细说。

首先我们先来看一个没有虚函数,即没有用到vTable的例子:

  1. #include <iostream>
  2. #include <ctime>
  3. using std::cout;
  4. using std::endl;

  5. struct Animal { void makeSound() { cout << "动物叫了" << endl; } };

  6. struct Cow : public Animal { void makeSound() { cout << "牛叫了" << endl; } };
  7. struct Pig : public Animal { void makeSound() { cout << "猪叫了" << endl; } };
  8. struct Donkey : public Animal { void makeSound() { cout << "驴叫了" << endl; } };

  9. int main(int argc, const char * argv[])
  10. {
  11.     srand((unsigned)time(0));
  12.     int count = 4;
  13.     while (count --) {
  14.         Animal *animal = nullptr;
  15.         switch (rand() % 3) {
  16.             case 0:
  17.                 animal = new Cow;
  18.                 break;
  19.             case 1:
  20.                 animal = new Pig;
  21.                 break;
  22.             case 2:
  23.                 animal = new Donkey;
  24.                 break;
  25.         }
  26.         animal->makeSound();
  27.         delete animal;
  28.     }
  29.     return 0;
  30. }
复制代码


程序中有一个基类Animal,它有一个makeSound()函数。有三个继承自Animal的子类,分别是牛、猪、驴,并且实现了自己的makeSound()方法。很简单的代码,是吧。

我们运行程序,你觉得输出结果会是什么呢?不错,这里会连续执行4次Animal的makeSound()方法,结果如下:


为什么?因为我们的基类Animal的makeSound()方法没有使用Virtual修饰,所以在静态编译时就makeSound()的实现就定死了。调用makeSound()方法时,编译器发现这是Animal指针,就会直接jump到makeSound()的代码段地址进行调用。

ok,那么我们把Animal的makeSound()改为虚函数,如下:


  1. struct Animal {
  2.     virtual void makeSound()
  3.         {
  4.            cout << "动物叫了" << endl;
  5.         }
  6. };
复制代码

运行会是怎样?如你所料,多态已经成功实现:



接下来就是大家最关心的部分,这是怎么回事?编译器到底做了什么?

虚表

为了说明方便,我们需要修改一下基类Animal的代码,不改变其他子类,修改如下:

[backcolor=rgb(248, 248, 255) !important][backcolor=rgb(238, 238, 238) !important]
  1. struct Animal {
  2.     virtual void makeSound() { cout << "动物叫了" << endl; }
  3.     virtual void walk() {}
  4.     void sleep() {}
  5. };

  6. struct Cow : public Animal { void makeSound() { cout << "牛叫了" << endl; } };
  7. struct Pig : public Animal { void makeSound() { cout << "猪叫了" << endl; } };
  8. struct Donkey : public Animal { void makeSound() { cout << "驴叫了" << endl; } };
复制代码

首先我们需要知道几个关键点:

  • 函数只要有virtual,我们就需要把它添加进vTable。
  • 每个类(而不是类实例)都有自己的虚表,因此vTable就变成了vTables。
  • 虚表存放的位置一般存放在模块的常量段中,从始至终都只有一份。详情可在此参考

我们怎么理解?从本例来看,我们的Animal、Cow、Pig、Donkey类都有自己的虚表,并且虚表里都有两个地址指针指向makeSound()和walk()的函数地址。一个指针4个字节,因此每个vTable的大小都是8个字节。如图:


他们的虚表中记录着不同函数的地址值。可以看到Cow、Pig、Donkey重写了makeSound()函数但是没有重写walk()函数。因此在调用makeSound()时,就会直接jump到自己实现的code Address。而调用walk()时,则会jump到Animal父类walk的Code Address。

虚指针

现在我们已经知道虚表的数据结构了,那么我们在堆里实例化类对象时是怎么样调用到相应的函数的呢?这就要借助到虚指针了(vPointer)。

虚指针是类实例对象指向虚表的指针,存在于对象头部,大小为4个字节,比如我们的Donkey类的实例化对象数据结构就如下


我们修改main函数里的代码,如下:

[backcolor=rgb(248, 248, 255) !important][backcolor=rgb(238, 238, 238) !important]
  1. int main(int argc, const char * argv[])
  2. {
  3.     int count = 2;
  4.     while (count --) {
  5.         Animal *animal = new Donkey;
  6.         animal->makeSound();
  7.         delete animal;
  8.     }
  9.     return 0;
  10. }
复制代码


我们在堆中生成了两个Donkey实例,运行结果如下:

[backcolor=rgb(248, 248, 255) !important][backcolor=rgb(238, 238, 238) !important]
  1. 驴叫了
  2. 驴叫了
  3. Program ended with exit code: 0
复制代码


没问题。然后我们再来看看堆里的结构,就变成了这样:


还有什么是这张图不能说明的呢?

Enjoy it

参考链接:
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|firemail ( 粤ICP备15085507号-1 )

GMT+8, 2024-4-29 05:48 , Processed in 0.062150 second(s), 22 queries .

Powered by Discuz! X3

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表