代码示例:
非虚析构的情况下.
#include#include using namespace std;class A{public: A() { std::cout << "A is created." << std::endl; } ~A() { std::cout << "A is deleted." << std::endl; }}; class B : public A{public: B() { std::cout << "B is created." << std::endl; } ~B() { std::cout << "B is deleted." << std::endl; }}; int main(){ A* pA = new B(); delete pA; return 0;}
虚析构的情况下.
#include#include using namespace std;class A{public: A() { std::cout << "A is created." << std::endl; } virtual ~A() { std::cout << "A is deleted." << std::endl; }}; class B : public A{public: B() { std::cout << "B is created." << std::endl; } ~B() { std::cout << "B is deleted." << std::endl; }}; int main(){ A* pA = new B(); delete pA; return 0;}
如果在类型B中创建了一些资源,比如文件句柄、内存等,在这种情况下都得不到释放,从而导致资源泄漏。