std::swap
是 C++ 标准库中的一个函数模板,位于 <algorithm>
头文件中(C++11 之前在 <utility>
中)。它的主要作用是交换两个对象的值。下面为你详细介绍它的用法、实现原理和示例。
copy-and-Swap
可以解决拷贝赋值函数中自赋值以及申请新内存可能导致异常的问题:
- 利用拷贝构造函数:
-
- 通过值传递参数(比如
String s
),调用拷贝构造函数创建一个临时对象。 - 如果拷贝构造函数抛出异常,不会影响当前对象的状态。
- 通过值传递参数(比如
- 交换资源:
-
- 使用
swap
函数将临时对象的资源与当前对象的资源交换。 swap
操作是noexcept
的,不会抛出异常。
- 使用
- 自动释放旧资源:
-
- 临时对象的析构函数会自动释放旧资源。
那什么是copy-and-swap
?直接看代码:
arduino
class String {
char *str;
public:
String &operator=(String s) // the pass-by-value parameter servrs as a temporary
{
s.swap(*this); // Non-throwing swap
return *this;
}
void swap(String &s) noexcept {
std::swap(this->str, s.str);
}
};
当然也可以:
arduino
class String {
char *str;
public:
String &operator=(const String &s) {
if (this != &s)
{
String(s).swap(*this); // Copy-constructor and non-throeing swap
}
// Old resources are released with the destruction of the temporrary abore
return *this;
}
void swap(String *s) noexcept
{
std::swap(this->str, s.str);
}
};
更优雅的写法是:
arduino
String &operator=(String s) {
s.swap(*this);
return *this;
}
void swap(String *s) noexcept
{
std::swap(this->str, s.str);
}
这种方式不仅方便,而且也做了进一步优化:
- 如果参数原来是个左值,会直接做拷贝,而其实这次拷贝无论在哪都无法避免
- 如果参数原来是右值或者临时对象,就节省了一次拷贝和析构,这也叫
copy elision
,这种operator
也就统一赋值运算符
In C++11, such an assignment operator is known as a unifying assignment operator because it eliminates the need to write two different assignment operators: copy-assignment and move-assignment. As long as a class has a move-constructor, a C++11 compiler will always use it to optimize creation of a copy from another temporary (rvalue). Copy-elision is a comparable optimization in non-C++11 compilers to achieve the same effect.
优点
- 异常安全:如果拷贝构造函数抛出异常,当前对象的状态不会被破坏。
- 代码简洁:不需要手动检查自赋值,也不需要显式释放资源。
- 支持移动语义(C++11 及以上):如果传递的是右值(临时对象),编译器会自动优化,调用移动构造函数而不是拷贝构造函数。
- 统一赋值运算符:一个赋值运算符同时支持拷贝赋值和移动赋值,减少了代码重复。
总结
copy-and-Swap
的核心:通过值传递参数调用拷贝构造函数,利用 swap 函数交换资源,确保异常安全。- 适用场景:适用于需要动态管理资源的类(如字符串、容器等)。
- 优点:异常安全、代码简洁、支持移动语义。
- 注意事项 :确保
swap
函数是noexcept
的,也要确保拷贝构造函数和析构函数正确实现。