缺省状态
只要类型T支持copy构造函数和copy assignment。
namespace std
{
template<typename T> // template<> 表示它是 std::swap 的一个全特化版本
void swap(T& a, T& b)// 函数名称后的 <Widget> 表示这一特化版本系针对 T是Widget 而设计
{
T temp(a);
a = b;
b = temp;
}
}
pimpl手法
只需要交换pImpl指针
class WidgetImpl
{
public:
…………
private:
int a, b, c;
std::vector<double> v;
…………
};
class Widget
{
public:
…………
void swap(Widget& other)
{
using std::swap; // 不用std::swap(pImpl, other.pImpl)
swap(pImpl, other.pImpl);
}
private:
WidgetImpl *pImpl;
};
namespace std
{
template<>
void swap<Widget>(Widget &a, Widget &b)
{
a.swap(b);
}
}