Effective C++: user-defined deleter.
Effective C++: user-defined deleter.
SHIHUAMarryMe 发表于2年前
Effective C++: user-defined deleter.
  • 发表于 2年前
  • 阅读 60
  • 收藏 0
  • 点赞 2
  • 评论 0

【腾讯云】新注册用户域名抢购1元起>>>   

std::shared_ptr与自定义deleter:

#include <iostream>
#include <memory>

class Deleter{
	public:
		Deleter()=default;
		~Deleter()=default;
		
		template<typename T, typename = 
		         typename std::enable_if<std::is_pointer<T>::value>::type>
		void operator()(T ptr)
		{
			if(ptr != nullptr){
				delete ptr;
			}
			
			std::cout<< "success!" << std::endl;
		}
};

template<typename T, typename =
         typename std::enable_if<std::is_pointer<T>::value>::type>
void deleter(T ptr)
{
	if(ptr != nullptr){
		delete ptr;
	}
	
	std::cout<< "success" << std::endl;
}
         

int main()
{
	//case 1:
	std::shared_ptr<int> p1(new int(20), Deleter());
	
	//case 2:
	std::function<void (int*)> deleterOne = std::bind(Deleter(), std::placeholders::_1);
	std::shared_ptr<int> p2(new int(30), deleterOne);
	
	//case 3:
	std::shared_ptr<int> p3(new int(40), deleter<int*>);
	
	//case 4:
	std::shared_ptr<int> p4(new int(50), [](int* ptr){ delete ptr; });
	
	
	return 0;
}

std::unique_ptr与自定义deleter:

#include <iostream>
#include <memory>
#include <functional>

class Deleter{
	public:
		Deleter()=default;
		~Deleter()=default;
		
		template<typename T, typename = 
		         typename std::enable_if<std::is_pointer<T>::value>::type>
		void operator()(T ptr)
		{
			if(ptr != nullptr){
				delete ptr;
			}
		}
};

template<typename T, typename = 
         typename std::enable_if<std::is_pointer<T>::value>::type>
void deleter(T ptr)
{
	if(ptr != nullptr){
		delete ptr;
	}
}

int main()
{
	//case 1:
	std::unique_ptr<int, Deleter> up1(new int, Deleter());
	
	//case 2:
	std::unique_ptr<int, std::function<void (int*)>> up2(new int, deleter<int*>);
	
	//case 3;
	std::unique_ptr<int, std::function<void (int*)>> up3(new int, [](int* ptr){ delete ptr; });
	
	//case 4:
	std::unique_ptr<int, std::function<void (int*)>> up4(new int, std::bind(Deleter(), std::placeholders::_1));
	
	
	return 0;
}

 

  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 12
博文 165
码字总数 138350
×
SHIHUAMarryMe
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: