简体   繁体   中英

std::unique_ptr and exception safety

Do I need to wrap std::unique_ptr usage with try/catch in code which should be exception safe?
std::unique_ptr will hold a raw memory block created by ::malloc (with my custom deleter to call ::free ).

  1. All of std::unique_ptr 's constructors * are noexcept
  2. malloc won't throw any exception on failure... it will just return nullptr .
  3. I believe your deleter's constructors won't throw anything either.

So you don't need to catch anything, since nothing will be thrown.


*: See C++11 §20.7.1.2.1 unique_ptr constructors [unique.ptr.single.ctor]

As mentioned in the comments, this answer is relevant for C++14 only .

Despite the good answer from @keenyt, it's worth to say that std::make_unique<T> can throw, even though the constructors of std::unique_ptr are noexcept .
Actually, whether the above mentioned statement throws or not mostly depends on the constructors of the type T involved.

As an example from cppreference.com for std::make_unique :

May throw std::bad_alloc or any exception thrown by the constructor of T. If an exception is thrown, this function has no effect.

So, a refinement of the answer would be: no, you don't need a try/catch block, unless you are using std::make_unique and the constructors of your type T can throw.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM