一、基类中析构函数不加关键字virtual。
1 #include <iostream> 2 using namespace std; 3 4 class Base 5 { 6 public: 7 ~Base() 8 { 9 cout<<"Base Destructor"<<endl; 10 } 11 }; 12 13 class Derive : public Base 14 { 15 public: 16 ~Derive() 17 { 18 cout<<"Derive Destructor"<<endl; 19 } 20 }; 21 22 int main() 23 { 24 Base *pBase = new Derive; 25 26 delete pBase; 27 28 return 0; 29 }
输出结果:
Base Destructor
二、基类析构函数加上关键字virtual
1 #include <iostream> 2 using namespace std; 3 4 class Base 5 { 6 public: 7 virtual ~Base() 8 { 9 cout<<"Base Destructor"<<endl; 10 } 11 }; 12 13 class Derive : public Base 14 { 15 public: 16 ~Derive() 17 { 18 cout<<"Derive Destructor"<<endl; 19 } 20 }; 21 22 int main() 23 { 24 Base *pBase = new Derive; 25 26 delete pBase; 27 28 return 0; 29 }
输出结果:
Derive Destructor
Base Destructor
可以看出,当我们用基类指针指向派生类时,如果我们delete基类的指针,如果基类析构函数不加virtual时,那么派生类的析构函数将得不到执行,那么此时就会造成内存泄漏,所以在此种情况下,我们应该把基类析构函数定义为虚析构函数,防止内存泄漏。