首页 > 代码库 > c++ 虚析构函数

c++ 虚析构函数

在实现多态时候,基类的析构函数应该写成virtual。在用基类申明实例化的子类对象,在delete时候,如果基类不是virtual的析构函数则不能调用进子类的析构函数

class Base{public:    Base();    virtual ~Base();public:    char *m_pName;};Base::Base(){     cout<<"Base()"<<endl;    m_pName = new char[1024];    memset(m_pName, 0, 1024);}Base::~Base(){    cout<<"~Base()"<<endl;    if (m_pName) {        delete [] m_pName;        m_pName = NULL;    }}class Child:public Base{public:    Child();    ~Child();public:    char *m_pAge;};Child::Child(){    cout<<"Child()"<<endl;    m_pAge = new char[2048];    memset(m_pAge, 0, 2048);}Child::~Child(){    cout<<"~Child()"<<endl;    if (m_pAge) {        delete [] m_pAge;        m_pAge = NULL;    }}int main(){    Base *pBase = new Child();    delete pBase;}输出如下:Base()Child()~Base()这样导致内存泄漏,因为子类的析构函数没有被调用。修改这类问题,把基类析构函数声明为virtual.
class Base{public:    Base();    virtual ~Base();public:    char *m_pName;};输出:Base()Child()~Child()~Base()

在没有virtual修饰下,是子类析构函数没有被调用。