std :: shared_ptr异常安全 [英] std::shared_ptr Exception Safety
问题描述
我刚刚意识到阅读本页时,std :: shared_ptr的构造函数只有一个指针参数也不例外.
I just realised reading this page that the constructor of std::shared_ptr with a single pointer argument is not noexcept.
因此,以下代码包含可能的内存泄漏:
Hence the following code contains a possible memory leak:
std::shared_ptr<int> p3 (new int);
原因是可能发生两种分配:
The reasonning is that two allocations could occure:
- 调用构造函数之前的第一个
- shared_ptr构造函数中的第二个(例如,在VS 2012中会发生这种情况)
这里有两个问题:
是真的,如果第二个分配抛出异常,则第一个分配的内存泄漏吗?
如果答案是肯定的:
使用std :: shared_ptr的正确习惯是什么?
- 使用make_shared
- 将第一个分配的所有权提供给std :: unique_ptr,然后转让所有权
- 其他想法吗?
推荐答案
template<class Y> explicit shared_ptr(Y* p);
[util.smartptr.shared.const]/6 抛出:bad_alloc
,或者当无法获得除内存以外的资源时的实现定义的异常.
[util.smartptr.shared.const]/7 <异常>安全性:如果引发异常,则调用delete p
.
[util.smartptr.shared.const]/6 Throws: bad_alloc
, or an implementation-defined exception when a resource other than memory could not be obtained.
[util.smartptr.shared.const]/7 Exception safety: If an exception is thrown, delete p
is called.
所以,没有内存泄漏.
这篇关于std :: shared_ptr异常安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!