强异常安全的swap通过拷贝和交换实现,先复制可能抛出异常,swap本身用noexcept交换指针和大小,确保赋值要么成功要么无影响。

在C++中,实现一个强异常安全的
swap
swap
swap
swap
实现强异常安全
swap
swap
假设我们有一个管理动态内存的类:
class MyResource {
private:
int* data;
size_t size;
<p>public:
explicit MyResource(size_t s = 0) : data(s ? new int[s] : nullptr), size(s) {}</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">~MyResource() { delete[] data; }
MyResource(const MyResource& other)
: data(other.size ? new int[other.size] : nullptr), size(other.size)
{
std::copy(other.data, other.data + size, data);
}
MyResource& operator=(MyResource other) // 注意:按值传参,自动调用拷贝构造
{
swap(*this, other); // 强异常安全:swap 不抛出异常
return *this;
}
friend void swap(MyResource& a, MyResource& b) noexcept
{
using std::swap;
swap(a.data, b.data);
swap(a.size, b.size);
}};
立即学习“C++免费学习笔记(深入)”;
other
swap
noexcept
other
这种设计确保了赋值操作满足强异常安全:要么赋值成功,要么原对象保持不变。
要确保
swap
noexcept
new
dynamic_cast
std::swap
swap
基本上就这些。只要 swap 本身不抛出异常,并在拷贝构造可能失败时推迟状态变更,就能实现强异常安全。这种模式在 RAII 类中非常普遍,是 C++ 异常安全编程的基石之一。
以上就是C++异常安全swap 强异常安全实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号