缺省状态
只要类型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);
}
}
本文介绍了C++标准库中的通用交换函数std::swap的实现原理,并展示了如何为特定类Widget定制该函数。此外,还探讨了使用pImpl惯技来优化Widget类成员交换的方法。

被折叠的 条评论
为什么被折叠?



