简体   繁体   English

Shared_ptr和unique_ptr有异常

[英]Shared_ptr and unique_ptr with exception

From en.cppreference.com 来自en.cppreference.com

Typical uses of std::unique_ptr include: std :: unique_ptr的典型用法包括:

  • 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 (eg if polymorphic behavior is desired) 移动感知容器中的元素类型,例如std :: vector,它保存指向动态分配对象的指针(例如,如果需要多态行为)

I am interested in the first point. 我对第一点感兴趣。

It is not mentioned for shared_ptr in cppreference.com. cppreference.com中的shared_ptr没有提到它。 I am not able to find a scenario where the shared_ptr doesn't get deleted when an exception is thrown. 我无法找到抛出异常时不会删除shared_ptr的场景。 Could someone please explain if there exists such possibilities ? 有人可以解释是否存在这样的可能性?

As the name suggest a std::shared_ptr shares it's pointer. 顾名思义, std::shared_ptr共享它的指针。 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. 如果抛出异常并且保留范围,则共享指针会被销毁,但如果某个地方存在另一个std::shared_ptr ,那么底层指针不会被删除,而只会减少引用计数器。

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. 由于std::unique_ptr唯一的,因此可以给出保证,因为我们知道它是唯一一个保持指针的保证。

Let's look into example as how std::unique_ptr can be used for providing exception safety: 让我们看看std::unique_ptr如何用于提供异常安全性的示例:

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? 那么shared_ptr可以用同样的方式来提供异常安全吗? 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. 所以它没有被提及作为这种情况的工具,但它并不意味着它不会删除拥有的对象,如果它是唯一的所有者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM