其他分享
首页 > 其他分享> > c – Shared_ptr和unique_ptr,但有异常

c – Shared_ptr和unique_ptr,但有异常

作者:互联网

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)

我对第一点感兴趣.

cppreference.com中的shared_ptr没有提到它.
我无法找到抛出异常时不会删除shared_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可以用同样的方式来提供异常安全吗?是的,它可以.但它不应该,因为它是为不同的目的而设计的,并且会产生不必要的开销.所以它没有被提及作为这种情况的工具,但它并不意味着它不会删除拥有的对象,如果它是唯一的所有者.

标签:c,shared-ptr,exception,unique-ptr
来源: https://codeday.me/bug/20190824/1705921.html