Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (e.g. 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 ?

like image 513
InQusitive Avatar asked Aug 10 '26 07:08

InQusitive


1 Answers

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.

like image 171
Slava Avatar answered Aug 14 '26 13:08

Slava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!