<五>智能指针之__自定义删除器

unique_ptr的成员函数在上面的博客中几乎全部涵盖,其实还有一个知识点,即std::unique_ptr::get_deleter字面已经很明显了,就获得deleter

智能指针采通过引用计数我们能解决多次释放同一块内存空间的问题,并且和之间直接移交管理权的方式比较这种方式更加灵活安全。但是这种方式也只能处理new出来的空间因为new要和析构中的delete匹配,为了使能和fopen的管理空间匹配,我们需要定制删除器

通过自定义删除器,可以实现一些场景下的资源释放和删除.

代码1

#include <iostream>
#include <thread>
using namespace std;

template <typename T>
class MyArrayDeletor {
public:
	void operator()(T *p ){
		cout << "call MyArrayDeletor" << endl;
		delete[] p;
		p = nullptr;
	}
	
};


int main() {
	{
	  unique_ptr<int, MyArrayDeletor<int>> ptr(new int[100]);
	}

	system("pause");
	return 0;
}

在这里插入图片描述

代码2,删除器_文件

#include <iostream>
#include <thread>
using namespace std;

template <typename T>
class MyFileDeletor {
public:
	void operator()(T *p) const {
		cout << "call MyFileDeletor" << endl;
		fclose(p);
		p = nullptr;
	}

};

int main() {
	{
	  unique_ptr<FILE, MyFileDeletor<FILE>> ptr(fopen("2.txt","w"));
	}

	system("pause");
	return 0;
}

加入lambda表达式和function,避免多个删除器类的定义,否则每自定义一个删除器,都要去写一个对应的类,太麻烦

#include <functional>

int main(){
	std::unique_ptr<int,function<void(int*)>> ptr1(new int[100],
		[](int*p)->void{
			cout<<"call my lambda deleter:int[]"<<endl;
			delete []p;
		}
	);
	std::unique_ptr<FILE,function<void(FILE*)>> ptr2(fopen("data.txt","w"),
		[](FILE*p)->void{
			cout<<"call my lambda deleter:FILE"<<endl;
			fclose(p);
		}
	);
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值