析构函数定义成虚函数是为了防止内存泄漏,因为当基类的指针或者引用指向或绑定到派生类的对象时,如果未将基类的析构函数定义成虚函数,会调用基类的析构函数,那么只能将基类的成员所占的空间释放掉,派生类中特有的就会无法释放内存空间导致内存泄漏。
比如以下程序示例:
C++
#include <iostream>
using namespace std;
class A {
private:
int val;
public:
~A() {
cout<<"A destroy!"<<endl;
}
};
class B: public A {
private:
int *arr;
public:
B() {
arr = new int[10];
}
~B() {
cout<<"B destroy!"<<endl;
delete arr;
}
};
int main() {
A *base = new B();
delete base;
return 0;
}
// A destroy!
我们可以看到如果析构函数不定义为虚函数,此时执行析构的只有基类,而派生类没有完成析构。我们将析构函数定义为虚函数,在执行析构时,则根据对象的类型来执行析构函数,此时派生类的资源得到释放。
C++
#include <iostream>
using namespace std;
class A {
private:
int val;
public:
virtual ~A() {
cout<<"A destroy!"<<endl;
}
};
class B: public A {
private:
int *arr;
public:
B() {
arr = new int[10];
}
virtual ~B() {
cout<<"B destroy!"<<endl;
delete arr;
}
};
int main() {
A *base = new B();
delete base;
return 0;
}
阅读量:2020
点赞量:0
收藏量:0