std::shared_ptr 异常安全

2023-09-26C/C++开发问题
15

本文介绍了std::shared_ptr 异常安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我刚刚意识到阅读这个页面,std::shared_ptr 带有单个指针参数不是 noexcept.

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.

所以不,没有内存泄漏.

So no, no memory leak.

这篇关于std::shared_ptr 异常安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6