unique_ptr智能指针的RAII在异常处理时的使用

1、今天读到一段poco的代码,对智能指针的使用有一些疑问

void registerClass(const std::string& className, AbstractFactory* pAbstractFactory)
		/// Registers the instantiator for the given class with the DynamicFactory.
		/// The DynamicFactory takes ownership of the instantiator and deletes
		/// it when it's no longer used.
		/// If the class has already been registered, an ExistsException is thrown
		/// and the instantiator is deleted.
{
	poco_check_ptr (pAbstractFactory);

	FastMutex::ScopedLock lock(_mutex);

	std::unique_ptr<AbstractFactory> ptr(pAbstractFactory);

	typename FactoryMap::iterator it = _map.find(className);
	if (it == _map.end())
		_map[className] = ptr.release();
	else
		throw ExistsException(className);
}

前置条件:_map存放的是普通指针;
疑问:
(1)为什么用unique_ptr来接收函数的参数指针;
(2)用unique_ptr如果正常插入map的话,又将指针的所有权转化给普通指针;

原因:
(1)如果正常添加到map表里,需要智能指针转移所有权;
(2)如果是else异常的话,智能指针可以释放,如果不用智能指针管理,
函数抛出异常的话,那函数指针就是泄露了;
主要就是智能指针的RAII在异常处理时的使用,这个知识点以前没有遇到过,特此记录一下;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值