c++ - std::shared_ptr 异常安全

标签 c++ c++11 memory-leaks shared-ptr

我刚刚意识到阅读 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/

相关文章:

c++ - 清理双向迭代器代码

c++ - CMake 与 Qt3d 用于 Qt5?

c++ - 为什么在返回临时(右值)时在 move 构造函数之前调用析构函数

c++ - std::atomic::load 的内存排序行为

c++ - 删除指针导致内存泄漏?

c - Cygwin 中的内存泄漏检测工具

c++ - 如果我删除类(class),shared_ptr 会被删除吗

c++ - 模板推导在 GCC 4.6 和 4.7 上的两个不同结果

c++ - 如何在 C++ 中的 UTF-8 上正确使用 std::string?

c - 获取内存泄漏但分配的内存已被释放