Shared_ptr和unique_ptr除外 [英] Shared_ptr and unique_ptr with exception
问题描述
std :: unique_ptr的典型用法包括:
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
作为可移动容器中的元素类型,例如std :: vector,
,其中包含指向动态分配对象的指针(例如,如果
需要多态行为)
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)
我对第一点感兴趣
在cppreferen中未提及 shared_ptr
ce.com。
我找不到当引发异常时,不会删除shared_ptr的情况。有人可以解释一下是否存在这种可能性吗?
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 ?
推荐答案
让我们来看一下 std如何: unique_ptr
可用于提供异常安全性:
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
所以我们应该使用:
std::unique_ptr<someclass> ptr = std::make_unique<someclass>();
... // no problem
简单,安全且没有开销。
simple, safe and no overhead.
那么可以使用 shared_ptr
来提供异常安全性吗?是的,它可以。但它不应这样做,因为它是为不同目的而设计的,并且会产生不必要的开销。因此,没有提到它是用于此类情况的工具,但这并不意味着如果它是唯一所有者,则不会删除拥有的对象。
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.
这篇关于Shared_ptr和unique_ptr除外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!