Shared_ptr and unique_ptr with exception

早过忘川 提交于 2019-12-10 20:37:12

问题


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 ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/35585569/shared-ptr-and-unique-ptr-with-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!