Shared_ptr 和 unique_ptr 有例外
Shared_ptr and unique_ptr with exception
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)
我对第一点感兴趣
cppreference.com 中的 shared_ptr
未提及。
我找不到抛出异常时 shared_ptr 不会被删除的场景。有人可以解释一下是否存在这种可能性吗?
顾名思义,std::shared_ptr
共享它的指针。如果抛出异常并离开范围,则共享指针将被销毁,但如果在某个地方有另一个 std::shared_ptr
是副本,则不会删除底层指针,而只是减少引用计数器。
这就是为什么他们不能保证一定会删除。由于 std::unique_ptr
是 唯一的 可以给出保证,因为我们知道它是唯一一个持有指针的人。
让我们看一下如何使用 std::unique_ptr
来提供异常安全性的示例:
someclass *ptr = new someclass;
...
delete ptr; // in case of exception we have problem
所以我们应该使用:
std::unique_ptr<someclass> ptr = std::make_unique<someclass>();
... // no problem
简单、安全且无开销。
那么shared_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
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)
我对第一点感兴趣
cppreference.com 中的 shared_ptr
未提及。
我找不到抛出异常时 shared_ptr 不会被删除的场景。有人可以解释一下是否存在这种可能性吗?
顾名思义,std::shared_ptr
共享它的指针。如果抛出异常并离开范围,则共享指针将被销毁,但如果在某个地方有另一个 std::shared_ptr
是副本,则不会删除底层指针,而只是减少引用计数器。
这就是为什么他们不能保证一定会删除。由于 std::unique_ptr
是 唯一的 可以给出保证,因为我们知道它是唯一一个持有指针的人。
让我们看一下如何使用 std::unique_ptr
来提供异常安全性的示例:
someclass *ptr = new someclass;
...
delete ptr; // in case of exception we have problem
所以我们应该使用:
std::unique_ptr<someclass> ptr = std::make_unique<someclass>();
... // no problem
简单、安全且无开销。
那么shared_ptr
可以用同样的方式来提供异常安全吗?是的,它可以。但它不应该,因为它是为不同的目的而设计的,并且会产生不必要的开销。所以它没有被提及作为这种情况的工具,但这并不意味着如果它是唯一的所有者它就不会删除拥有的对象。