C++ 不使用虚析构的后果及分析
很多 C++ 方面的书籍都说明了虚析构的作用:
- 保证派生类的析构函数被调用,并且使析构顺序与构造函数相反
- 保证资源能够被正确释放
很久一段时间以来,我一直认为第 2 点仅仅指的是:当派生类使用 RAII 手法时,如果派生类的析构没有被调用,就会产生资源泄露。就像下面的代码:
#include <iostream>
struct A
{
A() {
std::cout << "A::A" << std::endl;
}
~A() {
std::cout << "A::~A" << std::endl;
}
};
struct B : A
{
B() {
x = new int;
std::cout << "B::B" << std::endl;
}
~B() {
delete x;
std::cout << "B::~B" << std::endl;
}
int* x;
};
int main()
{
A* a = new B;
delete a;
}
这段代码结果输出:
A::A
B::B
A::~A
B 的析构函数没被调用,a->x 没有被正确释放,产生了内存泄漏。
后来发现在多重继承情况下,情况可能更加严重。例如以下代码:
#include <iostream>
struct A1
{
A1() : a1(0) {}
~A1() {
std::cout << "A1::~A1" << std::endl;
}
int a1;
};
struct A2
{
A2() : a2(0) {}
~A2() {
std::cout << "A2::~A2" << std::endl;
}
int a2;
};
struct B : A1, A2
{
B() : b(0) {}
~B() {
std::cout << "B::~B" << std::endl;
}
int b;
};
int main()
{
B* b = new B;
A1* a1 = b;
A2* a2 = b;
printf("%p %p %p\n", b, a1, a2);
delete a2;
}
输出:
0x5cbeb0 0x5cbeb0 0x5cbeb4
A2::~A2
free(): invalid pointer
已放弃 (核心已转储)
B* 隐式转型成 A2*,C++ 派生类指针(引用)转型为基类指针(引用)被称为 upcast。upcast 在单一继承的情况下,指针没有进行偏移,但是在多重继承下,会进行指针偏移。可以看到在多重继承下,第 2 个基类指针与派生类指针不同。再看 delete b 生成的汇编代码:
movq -40(%rbp), %rbx ; %rbx = a2
testq %rbx, %rbx ; a2 == 0 ?
je .L8
movq %rbx, %rdi ; A2's this ptr = a2
call A2::~A2() [complete object destructor]
movl $4, %esi
movq %rbx, %rdi
call operator delete(void*, unsigned long) ; call operator delete(a2, 4)
可以看到先调用了 A2::~A2(),再调用了 operator delete(a2, 12)。 传给底层 free() 函数的指针是 a2(0x5cbeb4),正确的指针应该是 b(0x5cbeb0)。而且第2个参数传递的是 4,是 A2 的大小,不是 B 的大小。free() 检测到这个是非法的指针,直接终止进程。给 A1 和 A2 的析构函数都加上 virtual,执行结果为:
0x1eb2eb0 0x1eb2eb0 0x1eb2ec0
B::~B
A2::~A2
A1::~A1
执行结果是正常的,再看此时生成的汇编代码:
movq -40(%rbp), %rax ; %rax = a2
testq %rax, %rax ; a2 == 0 ?
je .L13
movq (%rax), %rdx ; %rdx = vptr
addq $8, %rdx ; %rdx = vptr + 8
movq (%rdx), %rdx ; %rdx = vptr[1] or %rdx = *(vptr + 8)
movq %rax, %rdi ; %rax = vptr[1]
call *%rdx ; call vptr[1]
这段代码使用了虚函数,找到 B 的虚表:
vtable for B:
.quad 0
.quad typeinfo for B
.quad B::~B() [complete object destructor] ; vptr B inherit A1
.quad B::~B() [deleting destructor]
.quad -16
.quad typeinfo for B
.quad non-virtual thunk to B::~B() [complete object destructor] ; vptr B inherit A2
.quad non-virtual thunk to B::~B() [deleting destructor]
a2 的虚指针指向 non-virtual thunk to B::~B() [complete object destructor],会执行这个代码段:
non-virtual thunk to B::~B() [deleting destructor]:
subq $16, %rdi ; this = a2 - 16 or this = b, a2 downcast to b
jmp .LTHUNK1
由于 a2 != b,a2 要进行 downcast 变成 b,于是使用 thunk 技术进行指针偏移,再调用B::~B() [deleting destructor]。B::~B() [deleting destructor]再调用 B::~B(b),和 operator delete(b, 32)
.set .LTHUNK1,B::~B() [deleting destructor]
B::~B() [deleting destructor]:
pushq %rbp
movq %rsp, %rbp
subq $16, %rsp
movq %rdi, -8(%rbp) ; store this to stack
movq -8(%rbp), %rax ; %rax = this
movq %rax, %rdi
call B::~B() [complete object destructor] ; call B::~B(b)
movq -8(%rbp), %rax
movl $32, %esi
movq %rax, %rdi
call operator delete(void*, unsigned long) ; call operator delete(b, 32)
leave
ret
可以看到传递给 operator delete 的指针和大小是正确的。A2::~A2() 和 A1::~A1() 在 B::~B() [complete object destructor] 中被调用,不需要继续深入观察。
虚析构完美解决了这两个问题:
- 派生类的析构函数没有被调用
- 传递给底层
free()函数的指针是错误的
在 ISO/IEC 14882:2011 5.3.3 也有对不使用虚析构的描述
In the first alternative (delete object), if the static type of the object to be deleted is different from its
dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the
static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete
array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.
C++ 不使用虚析构的后果及分析的更多相关文章
- C++的虚析构
最近准备复习一遍所有的知识点,先从基础开始做起,用几分钟写个继承和析构吧. 父类为A,子类为B,代码如下: class A { public: A() { cout << "构造 ...
- C++——虚析构
目的: //只执行了 父类的析构函数//向通过父类指针 把 所有的子类对象的析构函数 都执行一遍//向通过父类指针 释放所有的子类资源 方法:在父类的析构函数前+virtual关键字 #define ...
- C++中虚析构的作用
为了当用一个基类的指针删除一个派生类的对象时,派生类的析构函数会被调用. 基本概念: 析构函数是用来回收对象的: 虚析构函数是析构函数的一种: 基类是一类对象共有属性的抽象.比如,猫和狗都是动物,都会 ...
- C++ //虚析构和纯虚析构
1 //虚析构和纯虚析构 2 3 #include <iostream> 4 #include <string> 5 using namespace std; 6 7 clas ...
- nova start 虚机的代码流程分析
nova start 虚机的代码流程分析,以ocata版本为分析基础1.nova api服务接受用户下发的 nova start启动虚机请求其对应的http restfull api接口为post / ...
- C++基础知识 基类指针、虚函数、多态性、纯虚函数、虚析构
一.基类指针.派生类指针 父类指针可以new一个子类对象 二.虚函数 有没有一个解决方法,使我们只定义一个对象指针,就可以调用父类,以及各个子类的同名函数? 有解决方案,这个对象指针必须是一个父类类型 ...
- C++ 虚析构(virtual destructor)原理
注意:本文仅为个人理解,可能有误! 先看一段代码: #include <iostream> using namespace std; class CBase{ public: CBase( ...
- C++构造函数调用虚函数的后果
#include <iostream> class cx { public: virtual void func() { std::cout << "func&quo ...
- 类虚函数表原理实现分析(当我们将虚表地址[n]中的函数替换,那么虚函数的实现就由我们来控制了)
原理分析 当调用一个虚函数时, 编译器生成的代码会调用 虚表地址[0](param1, param2)这样的函数. 已经不是在调用函数名了. 当我们将虚表地址[n]中的函数实现改为另外的函数, 虚函数 ...
- java中的软,弱,虚引用介绍与特性分析
java的弱,虚,软引用介绍 1.弱,虚,软引用的介绍 对于绝大部分的对象而言,在程序中是存在着一个引用变量引用该对象,这是常见的引用方式,也就是常说的 强引用,对于强引用引用的对象,系统JVM是不会 ...
随机推荐
- 如何将 performance_schema 中的 TIMER 字段转换为日期时间
问题 最近有好几个朋友问,如何将 performance_schema.events_statements_xxx 中的 TIMER 字段(主要是TIMER_START和TIMER_END)转换为日期 ...
- 精致的Javascript代码
1. 统计一个数组中,每个值的个数 var cards = [1, 2, 3, 4, 3, 2, 1, 4, 5] var dict = {}; for(var i = 0; i < cards ...
- Git恢复删除的文件,一行命令就可以啦~
情况一:删除或者修改了某个文件,但是没有add # 单个 git checkout filename # 多个 git checkout . 情况二:删除或者修改了某个文件,已经add,但是没有com ...
- HDU-2586 How far away?
There are n houses in the village and some bidirectional roads connecting them. Every day peole alwa ...
- AntDesignBlazor示例——Modal表单
本示例是AntDesign Blazor的入门示例,在学习的同时分享出来,以供新手参考. 示例代码仓库:https://gitee.com/known/BlazorDemo 1. 学习目标 创建Mod ...
- 华企盾防泄密软件关于U盘无法注册问题
1.以管理员权限运行控制台注册 2.如果是非加密注册可在USB拔插日志中右键日志远程注册 3.检查USB的驱动程序注册表是否都有 4.换一台电脑安装控制台注册 5.检查是否有与驱动有关的程序卸载试试 ...
- 使用cgroup控制内存
关键文件 memory.limit_in_bytes memory.soft_limit_in_bytes memory.memsw.limit_in_bytes tasks cgroup.procs ...
- JavaFx 打包jar(六)
JavaFx 打包jar(六) JavaFX 从入门入门到入土系列 我们编写了不少javafx,那么如何打包成jar给用户呢?下面我给出比较全的打包方式. 打包jar 下面我给出比较全的打包方式. 1 ...
- win10 安装 AutoCAD
有些人在 win10 系统下 安装 AutoCAD 会有些小问题,不要担心,根据下面这些图片就可以解决你的问题 答案很简单,就是安装.NET Framework3.5,这里提供一种安装方法供大家参考: ...
- 十分钟教你在 k8s 中部署一个前后端应用
转载至我的博客https://www.infrastack.cn ,公众号:架构成长指南 大家好,我是蜗牛哥,好多开发人员,尤其是没接触过 k8s 的人员对如何在k8s中部署一个 前后端应用很模糊,不 ...