作者:jicanmeng
时间:2014年12月05日
先看一个程序:
#include <iostream> using namespace std; class Base { public: ~Base(){ cout << "Calling ~Base()" << endl; } }; class Derived: public Base { private: int* m_pnArray; public: Derived(int nLength){ m_pnArray = new int[nLength]; } ~Derived(){ cout << "Calling ~Derived()" << endl; delete[] m_pnArray; } }; int main() { Derived *pDerived = new Derived(5); Base *pBase = pDerived; delete pBase; return 0; }
上面的程序中,程序退出之前,我们调用delete pBase;
,但是这行代码只会调用Base的析构函数,不会调用Derived的析构函数,会产生内存泄露。可以通过将Base的析构函数设置为虚函数来解决这个问题。
#include <iostream> using namespace std; class Base { public: virtual ~Base(){ cout << "Calling ~Base()" << endl; } }; class Derived: public Base { private: int* m_pnArray; public: Derived(int nLength){ m_pnArray = new int[nLength]; } virtual ~Derived(){ cout << "Calling ~Derived()" << endl; delete[] m_pnArray; } }; int main() { Derived *pDerived = new Derived(5); Base *pBase = pDerived; delete pBase; return 0; }