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在异常处理时的使用,这个知识点以前没有遇到过,特此记录一下;