我刚刚意识到阅读 this page std::shared_ptr
的构造函数只有一个指针参数不是 noexcept。
因此以下代码包含可能的内存泄漏:
std::shared_ptr<int> p3 (new int);
原因是可能发生两次分配:
- 调用构造函数之前的第一个
- 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 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.
所以不,没有内存泄漏。
关于c++ - std::shared_ptr 异常安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20053504/