标签:c shared-ptr exception 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 exceptionpassing ownership of uniquely-owned objects with dynamic lifetime into
functionsacquiring ownership of uniquely-owned objects with dynamic lifetime
from functionsas 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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。