虚析构函数
在C++中,析构函数最好定义为虚函数,在类成员中有需要程序员自己申请和释放的成员,比如说指针类型的成员时,当用父类指针指向子类,虚析构函数能够使父类的指针正确地调用属于子类的析构函数,下面是一个例子:
#include <iostream>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(int argc, char** argv){A* pA = new B();delete pA;return 0;}
可以看到delete pA调用的是A类的析构函数,B类中没有创建一些特殊的资源,如文件句柄,内存空间之类,所以这么delete没问题,但是如果申请了的话,这样会造成内存泄露。正确的写法应该是这样的:
#include <iostream>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(int argc, char** argv){A* pA = new B();
delete pA;
return 0;
}
可以看到,确定为基类的类的析构函数设为虚函数之后可以避免这一问题