C ++中的虚拟析构函数 [英] virtual destructor in c++
问题描述
在下面的代码中,为什么自动调用~Derived()
析构函数?
In the code below, why is the ~Derived()
destructor called automatically?
#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;
}
推荐答案
因为您的基类析构函数是虚拟的
Because your base class destructor is virtual
virtual ~Base();
对指向基类的指针的delete调用会导致对析构函数的虚拟调用,并且任何虚拟调用都会分派到派生类中的匹配函数.这不仅好,而且是必要的;否则,行为是不确定的.
the call to delete on a pointer to a base class results in virtual call to destructor and as any virtual call is dispatched to matching function in derived class. It is not only good, but necessary: otherwise the behavior is undefined.
这对于析构函数不是空函数的派生类至关重要.非虚拟调用会导致调用基类析构函数,派生资源被泄漏等.
This is crucial for a derived classes which destructor is not an empty function. Non-virtual call would otherwise result in calling base class destructor, derived resources being leaked, etc.
这篇关于C ++中的虚拟析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!