虚析构函数

#include <iostream>
using namespace std;

class A {
public:
	A() { cout << "call A()" << endl; }
	~A() { cout << "call ~A()"; }
};

class B:public A {
	char *buf;
public:
	B() { buf = new char[100]; cout << "call B()" << endl; }
	~B() { delete []buf; cout << "call ~B()" << endl; }
};

int main(void)
{
	A *p = new B;
	delete p;

	return 0;
}

输出:

 

call A()
call B()
call ~A()

并没有调用~B(),  从而导致100字节的内存没有被释放。

 

将A的析构函数说明为虚函数可解决此问题。

#include <iostream>
using namespace std;

class A {
public:
	A() { cout << "call A()" << endl; }
	virtual ~A() { cout << "call ~A()"; }
};

class B:public A {
	char *buf;
public:
	B() { buf = new char[100]; cout << "call B()" << endl; }
	~B() { delete []buf; cout << "call ~B()" << endl; }
};

int main(void)
{
	A *p = new B;
	delete p;

	return 0;
}
 
输出:

call A()
call B()
call ~B()
call ~A()

posted @ 2012-12-31 22:28  helloweworld  阅读(143)  评论(0编辑  收藏  举报