当前位置:网站首页>The use of RAII of unique_ptr smart pointer in exception handling

The use of RAII of unique_ptr smart pointer in exception handling

2022-09-23 08:36:29hhaijiuwo

1. I read a piece of poco code today and have some questions about the use of smart pointers

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();elsethrow ExistsException(className);}

Preconditions: _map stores ordinary pointers;
Questions:
(1) Why use unique_ptr to receive function parameter pointers;
(2) If unique_ptr is used to insert map normally, thenConvert the ownership of the pointer to a normal pointer;

Reason:
(1) If it is added to the map table normally, the ownership of the smart pointer needs to be transferred;
(2) If it is an else exception, the smart pointer can be released. If it is not managed by the smart pointer,
> If the function throws an exception, the function pointer is leaked;
The main reason is the use of RAII of smart pointers in exception handling. This knowledge point has not been encountered before, so I will record it here;

原网站

版权声明
本文为[hhaijiuwo]所创,转载请带上原文链接,感谢
https://chowdera.com/2022/266/202209230827317090.html

随机推荐