内存泄漏-消失的析构函数

#include<iostream>
using namespace std;


class Father {
public:
	Father(const char * Name="中国") {
		int len = strlen(Name)+1;
		this->Name = new char[len];
		strcpy_s(this->Name, len, Name);
		cout << "调用父类构造函数" << endl;
	}
	~Father() {
		if (Name) {
			delete Name;
			Name = NULL;
			cout << "调用父类析构函数" << endl;
		}
	}
private:
	char* Name;
};

class Son :public Father {
public:
	Son (const char* Game = "游戏") {
		int len = strlen(Game)+1;
		this->Game = new char[len];
		strcpy_s(this->Game, len, Game);
		cout << "调用子类构造函数" << endl;
	}
	~Son() {
		if (Game) {
			delete Game;
			Game = NULL;
			cout << "调用子类析构函数" << endl;
		}
	}
private:
	char* Game;
};

int main()
{
	cout << "**************case 1:***************" << endl;
	Father *father=new Father();
	delete father;
	cout << "**************case 2:***************" << endl;
	Son* son = new Son();
	delete son;
	cout << "**************case 3:***************" << endl;
	Father* f = new Son();
	delete f;
	return 0;


}

结果如下:

在这里插入图片描述
可以看见case3并没有调用子类析构函数
会导致子类中的内存没法释放而导致泄露

原因:
C++特性 在用子类给父类对象实例化的时候会导致析构的时候只调用父类的析构函数

解决方案:

virtual ~Father() {
		if (Name) {
			delete Name;
			Name = NULL;
			cout << "调用父类析构函数" << endl;
		}
	}
在父类前面加上virtual即可 而且注意保持好习惯 需要作为基类的函数最好加上virtual
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值