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$