简体   繁体   中英

Shared_ptr and unique_ptr with exception

From en.cppreference.com

Typical uses of std::unique_ptr include:

  • providing exception safety to classes and functions that handle objects with dynamic lifetime, by guaranteeing deletion on both normal exit and exit through exception

  • passing ownership of uniquely-owned objects with dynamic lifetime into functions

  • acquiring ownership of uniquely-owned objects with dynamic lifetime from functions

  • as the element type in move-aware containers, such as std::vector, which hold pointers to dynamically-allocated objects (eg if polymorphic behavior is desired)

I am interested in the first point.

It is not mentioned for shared_ptr in cppreference.com. I am not able to find a scenario where the shared_ptr doesn't get deleted when an exception is thrown. Could someone please explain if there exists such possibilities ?

As the name suggest a std::shared_ptr shares it's pointer. If an exception is thrown and the scope is left the shared pointer gets destroyed but if there is another std::shared_ptr somewhere that is a copy then the underlying pointer is not deleted but instead just the reference counter is decremented.

This is why they cannot guarantee the deletion will happen. Since std::unique_ptr is unique the guarantee can be given as we know it is the only one holding onto the pointer.

Let's look into example as how std::unique_ptr can be used for providing exception safety:

someclass *ptr = new someclass;
...
delete ptr; // in case of exception we have problem

so instead we should use:

std::unique_ptr<someclass> ptr = std::make_unique<someclass>();
... // no problem

simple, safe and no overhead.

So can shared_ptr be used same way to provide exception safety? Yes it can. But it should not, as it is designed for different purpose and would have unnecessary overhead. So it is not mentioned as a tool for such cases, but it does not mean it would not delete owned object if it is the only owner.

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