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是不会 ...
随机推荐
- 文心一言 VS 讯飞星火 VS chatgpt (157)-- 算法导论12.3 4题
四.用go语言,删除操作可交换吗?可交换的含义是,先删除 x 再删除 y 留下的结果树与先除 y 再删除 x 留下的结果树完全一样.如果是,说明为什么? 否则,给出一个反例. 文心一言: 在Go语言中 ...
- 使用Py2neo更新Neo4j中节点的属性值的正确姿势
1 def findNode(name, graph): 2 matcher = NodeMatcher(graph) 3 m = matcher.match(name = name).first() ...
- XILINX HLS 入坑记录 之 写RAM 综合出 读取+写入Ram
最近使用 Xilinx HLS 来开发 算法的IPcore,使用的Vitis 2021,发现光是 EDA 工具就存在很多的bug,比如: 1.经常C综合 停留在 Using flow_target ' ...
- vue3组合式api生命周期
生命周期钩子函数 Vue3:https://cn.vuejs.org/api/composition-api-lifecycle.html Vue2:https://v2.cn.vuejs.org/v ...
- 华企盾DSC无法从网页下载客户端(无法访问web端)
解决方法1:服务器安装目录需要安装在英文目录,否则DSCApache.exe会启动不了,导致无法访问5580网页. 解决方法2:5580端口占用也会导致DSCApache.exe启动不了,可打开服务器 ...
- 华企盾DSC发送白名单提示“解密发送失败”(被中转服务器判定为垃圾邮箱)
解决方法:用DebugView监控,发现含有550错误,说明中转服务器被判定为垃圾邮箱,换一个中转邮箱或者设置为无中转发送 还有一种可能:邮箱设置了收到邮箱后自动删除 DebugView中显示上图 ...
- idea2020.1.3汉化包报错问题
已解决:idea2020.1.3汉化包报错问题 问题描述:插件市场提供的版本不对.不兼容,所以需要手动下载安装 这里附上文件 https://wwsi.lanzouq.com/b03czdtwf 密码 ...
- 【2】从零玩转OSS阿里云存储服务之Java代码操作-2-cong-ling-wan-zhuan-oss-a-li-yun-cun-chu-fu-wu-zhi-java-dai-ma-cao-zuo
title: [2]从零玩转OSS阿里云存储服务之Java代码操作 date: 2021-06-09 17:37:14.486 updated: 2021-12-26 17:43:12.779 url ...
- Gateway:Spring Cloud API网关组件
Gateway:Spring Cloud API网关组件 问题总结 API网关? Spring Cloud Gateway? GateWay的工作流程?(重点) Predicate断言? Filter ...
- zabbix常用监控项
https://blog.csdn.net/xkjcf/article/details/78559273?locationNum=10&fps=1 agent.ping #agent是否在线 ...