您的位置:首页 > 编程语言 > C语言/C++

[effectiv c++]条款25:考虑写出一个不抛出异常的swap函数(pimpl手法)

2017-09-19 19:16 477 查看
缺省状态

只要类型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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: