本文主要是介绍虚析构函数(C++),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- 4.3 虚析构函数
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$
这篇关于虚析构函数(C++)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!