其他分享
首页 > 其他分享> > 虚析构函数的作用

虚析构函数的作用

作者:互联网

虚析构函数的作用就是用父类指针或者引用释放所有的子类资源。

 

在没有使用虚析构函数的情况下,因为c++是静态联编语言,其指针是什么类型,就默认为指针指向的是什么类型,因为这样做是绝对安全的,我也非常支持这种做法,但是,在有些时候,确是会出现问题,具体看如下代码:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class A
{
public:
	A()
	{
		p = new char[20];
		strcpy(p, "obja");
		printf("A()\n");
	}
	~A()
	{
		delete [] p;
		printf("~A()\n");
	}
protected:
private:
	char* p;
};

class B : public A
{
public:
	B()
	{
		p = new char[20];
		strcpy(p, "objb");
		printf("B()\n");
	}
	~B()
	{
		delete [] p;
		printf("~B()\n");
	}
protected:
private:
	char* p;
};

class C : public B
{
public:
	C()
	{
		p = new char[20];
		strcpy(p, "objc");
		printf("C()\n");
	}
	virtual ~C()
	{
		delete [] p;
		printf("~C()\n");
	}
protected:
private:
	char* p;
};

void HowToDeleteA(A* base)
{
	delete base;
}

void HowToDeleteB(B* base)
{
	delete base;
}

int main()
{
	A* baseA = new C;
	B* baseB = new C;
	cout << "hello world" << endl;
	HowToDeleteA(baseA);  //这个函数会输出 ~A(),不符合预期
	HowToDeleteB(baseB);  //这个函数会输出 ~B()和~A(), 不符合预期
	return 0;
} 

在使用了虚析构函数只会,输出情况会变成如下所示:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class A
{
public:
	A()
	{
		p = new char[20];
		strcpy(p, "obja");
		printf("A()\n");
	}
	virtual ~A()
	{
		delete [] p;
		printf("~A()\n");
	}
protected:
private:
	char* p;
};

class B : public A
{
public:
	B()
	{
		p = new char[20];
		strcpy(p, "objb");
		printf("B()\n");
	}
	virtual ~B()
	{
		delete [] p;
		printf("~B()\n");
	}
protected:
private:
	char* p;
};

class C : public B
{
public:
	C()
	{
		p = new char[20];
		strcpy(p, "objc");
		printf("C()\n");
	}
	virtual ~C()
	{
		delete [] p;
		printf("~C()\n");
	}
protected:
private:
	char* p;
};

void HowToDeleteA(A* base)
{
	delete base;
}

void HowToDeleteB(B* base)
{
	delete base;
}

int main()
{
	A* baseA = new C;
	B* baseB = new C;
	cout << "hello world" << endl;
	HowToDeleteA(baseA);  //使用了虚析构函数,相当于调用delete C,输出: ~C,~B,~A (构造函数调用顺序与析构函数调用顺序正好相反)
	HowToDeleteB(baseB);  //使用了虚析构函数,相当于调用delete C, 输出: ~C,~B,~A
	return 0;
} 

总之,虚析构函数的作用是使用父类指针或者引用释放所有的子类资源

tianguiyuyu 发布了220 篇原创文章 · 获赞 85 · 访问量 21万+ 私信 关注

标签:函数,public,char,base,printf,new,虚析构,作用,delete
来源: https://blog.csdn.net/tianguiyuyu/article/details/104553874