您的位置:首页 > 移动开发 > Objective-C

条款25:考虑写出一个不抛异常的swap函数

2010-03-05 10:18 351 查看
 "pimpl idiom"("pointer to implementation" )的设计方式:交换这两个 Widget 对象的值,我们实际要做的就是交换它们的 pImpl 指针

 

class WidgetImpl { // class for Widget data;
public: // details are unimportant
...
private:
int a, b, c; // possibly lots of data -
std::vector<double> v; // expensive to copy!
...
};
class Widget { // class using the pimpl idiom
public:
Widget(const Widget& rhs);
Widget& operator=(const Widget& rhs) // to copy a Widget, copy its
{
// WidgetImpl object. For
... // details on implementing
*pImpl = *(rhs.pImpl); // operator= in general,
... // see Items 10, 11, and 12.
}
...
private:
WidgetImpl *pImpl; // ptr to object with this Widget’s data
};


 

类型Widge完全特化标准模板:

class Widget { // same as above, except for the addition of the swap mem func
public:
...
void swap(Widget& other)
{
using std::swap; // the need for this declaration is explained later in this Item
swap(pImpl, other.pImpl); // to swap Widgets, swap their pImpl pointers
}
...
};
namespace std {
template<> // revised specialization of
void swap<Widget>(Widget& a, Widget& b) // std::swap
{
a.swap(b); // to swap Widgets, call their swap member function
}
}


 

当Widget和WidgetImpl是类模板,而不是类时怎么办?:

namespace WidgetStuff { // templatized WidgetImpl, etc.
...
template<typename T> // as before, including the swap
class Widget { ... }; // member function
...
template<typename T> // non-member swap function;
void swap(Widget<T>& a, Widget<T>& b) // not part of the std namespace
{
a.swap(b);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息