虚析构函数(C++)

2024-01-07 22:54:19

4.3 虚析构函数

C++允许将析构函数定义为虚函数,为什么?

#include <iostream>
using namespace std;

class Base{
public:
	Base(){
		cout << "Base 通过 new 申请100个字节内存空间" << endl;
	}
	~Base(){
		cout << "~Base 通过 delete 释放100个字节内存空间" << endl;
	}
};

class Derived:public Base{
public:
	Derived(){
		cout << "Derived 通过 new 申请200个字节内存空间" << endl;
	}
	~Derived(){
		cout << "~Derived 通过 delete 释放200个字节内存空间" << endl;
	}
};

int main(void) {
	
	Base *pb = new Derived;

	delete pb; //只调用了基类的析构函数 造成内存泄漏
	return 0;
}
//输出结果  
myubuntu@ubuntu:~/lv19/cplusplus/dy05$ ./a.out 
Base 通过 new 申请100个字节内存空间
Derived 通过 new 申请200个字节内存空间
~Base 通过 delete 释放100个字节内存空间

如何解决该问题?将基类析构函数定义为虚函数

#include <iostream>
using namespace std;

class Base{
public:
	Base(){
		cout << "Base 通过 new 申请100个字节内存空间" << endl;
	}
	virtual ~Base(){  //定义为虚函数
		cout << "~Base 通过 delete 释放100个字节内存空间" << endl;
	}
};

class Derived:public Base{
public:
	Derived(){
		cout << "Derived 通过 new 申请200个字节内存空间" << endl;
	}
	~Derived(){
		cout << "~Derived 通过 delete 释放200个字节内存空间" << endl;
	}
};

int main(void) {
	
	Base *pb = new Derived;

	delete pb;
	return 0;
}
//输出结果  
myubuntu@ubuntu:~/lv19/cplusplus/dy05$ ./a.out 
Base 通过 new 申请100个字节内存空间
Derived 通过 new 申请200个字节内存空间
~Derived 通过 delete 释放200个字节内存空间
~Base 通过 delete 释放100个字节内存空间
myubuntu@ubuntu:~/lv19/cplusplus/dy05$ 

文章来源:https://blog.csdn.net/qq_36091214/article/details/135431754
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。