没有使用虚析构函数可能会出现的问题:
#include <iostream> #include <string> using namespace std; class A { public: A() { cout << " A constructor " << endl; } ~A() { cout << " A destructor " << endl; } }; class B: public A { char *buf; public: B() { buf = new char [10]; cout << " B constructor " << endl; } ~B() { cout << " B destructor " << endl; } }; int main() { A *p = new B; delete p; // p是基类类型指针,仅调用基类析构函数,造成B中申请的10字节内存没被释放。 return 0; }
输出:
A constructor
B constructor
A destructor
解决:将基类中的析构函数定义为虚析构函数
#include <iostream> #include <string> using namespace std; class A { public: A() { cout << " A constructor " << endl; } virtual ~A() { cout << " A destructor " << endl; } }; class B: public A { char *buf; public: B() { buf = new char [10]; cout << " B constructor " << endl; } ~B() { cout << " B destructor " << endl; } }; int main() { A *p = new B; delete p; //A中的析构函数说明为虚析构函数后,B中析构函数自动成为虚析构函数,由于P
//指向派生类对象,因此会调用派生类B的析构函数。
return
0;
}
输出:
A constructor
B constructor
B destructor
A destructor