gpt4 book ai didi

c++ - 了解 shared_ptr::void reset (U* p) 的异常安全;

转载 作者:行者123 更新时间:2023-11-30 02:35:20 31 4
gpt4 key购买 nike

我正在尝试了解 template <class U> void shared_ptr::reset (U* p); 的异常安全性功能。 In the documentation我发现了这个:

Additionally, a call to this function has the same side effects as if shared_ptr's destructor was called before its value changed (including the deletion of the managed object if this shared_ptr was unique).

因此,我们可以假设析构函数不会抛出异常。但是如果operator new怎么办? throw ? shared_ptr什么状态那我们会有吗?是否保持不变?

最佳答案

根据 [util.smartptr.shared.mod],shared_ptr::reset(stuff) 的所有四个重载完全等同于

shared_ptr(stuff).swap(*this)

如果构造 shared_ptr(stuff) 抛出(例如,如果分配新的控制 block (或实现使用的任何等效机制)抛出),则 *this 是不受影响,因为您永远不会到达 swap,并且在 stuff 中传递的任何指针都会被适当删除(因为这是由 shared_ptr 的构造函数保证的)。

swap 本身不会抛出,因此在交换后销毁临时 shared_ptr

关于c++ - 了解 shared_ptr::void reset (U* p) 的异常安全;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33748965/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com