C++11 之前,只能使用拷贝构造和拷贝赋值:
template <typename T>
void swap(T& a, T& b) {
T t = a;
b = a;
b = t;
}
C++11 之后,如果类型 T
实现了移动语义,则可以避免拷贝;若未实现移动语义,则与之前相同:
template <typename T>
void swap(T& a, T& b) {
T t = std::move(a);
a = std::move(b);
b = std::move(t);
}