析构函数不使用virtual的情况:
class base
{
public:
base() {cout<<"construct base"<<endl;}
~base() {cout<<"destroy base"<<endl;}
};
class derived:public base
{
public:
derived() {cout<<"construct derived"<<endl;}
~derived() {cout<<"destroy derived"<<endl;}
};
int main()
{
derived* d = new derived;
delete d;
cout<<endl;
base* b = new derived;
delete b;
return 1;
}
输出:
析构函数使用virtual的情况:
class base
{
public:
base() {cout<<"construct base"<<endl;}
virtual ~base() {cout<<"destroy base"<<endl;}
};
class derived:public base
{
public:
derived() {cout<<"construct derived"<<endl;}
~derived() {cout<<"destroy derived"<<endl;}
};
int main()
{
derived* d = new derived;
delete d;
cout<<endl;
base* b = new derived;
delete b;
return 1;
}
输出:
总结:
在多态中,不使用virtual时,子类在释放时不会调用父类的析构函数,会造成内存泄露。