新网站如何做百度收录,flask做网站工具,做资讯网站需要哪些资质,漳州网站开发找出博大科技c中虚析构函数的作用是什么#xff1f;析构函数是为了在对象不被使用后释放它的资源#xff0c;虚函数是为了实现多态。那么#xff0c;把析构函数声明为virtual有什么作用呢#xff1f; 请看下面代码#xff1a;span stylefont-size:18px;#include 中虚析构函数的作用是什么析构函数是为了在对象不被使用后释放它的资源虚函数是为了实现多态。那么把析构函数声明为virtual有什么作用呢 请看下面代码span stylefont-size:18px;#include iostream using namespace std; class Base
{
public: Base(){ } //Base的构造函数 ~Base() //Base的析构函数 { coutoutput from the destructor of class Baseendl; } virtual void Dosomething() { coutdo something in class Baseendl; }
}; class Derived : public Base
{
public: Derived(){ } //Derived的构造函数 ~Derived() //Derived的析构函数 { coutoutput from the destructor of class Derivedendl; } void Dosomething() { coutdo something in class Derivedendl; }
}; int main()
{ Derived *pt1 new Derived(); pt1-Dosomething(); delete pt1; Base *pt2 new Derived(); pt2-Dosomething(); delete pt2; return 0;
}/span
程序输出
span stylefont-size:18px;do something in class Derived
output from the destructor of class Derived
output from the destructor of class Base
do something in class Derived
output from the destructor of class Base/span
代码37行可以正常释放pt1的资源但是代码41行并没有正常释放pt2的资源从结果看Derived类的析构函数并没有被调用。通常情况下类的析构函数里面都是释放内存资源而析构函数不被调用的话就会造成内存泄漏。原因是指针pt2是Base类型的指针释放pt2时只进行Base类的析构函数。在代码第9行加上virtual关键字后do something in class Derived output from the destructor of class Derived output from the destructor of class Base do something in class Derived output from the destructor of class Derived output from the destructor of class Base
此时释放指针pt2时由于Base的析构函数是virtual的就会先找到并执行Derived类的析构函数然后执行Base类的析构函数资源正常释放避免了内存泄漏。因此只有当一个类被用来作为基类的时候才会把析构函数写成虚析构函数。