条款25:考虑写出一个不抛异常的swap函数
2010-03-05 10:18
351 查看
"pimpl idiom"("pointer to implementation" )的设计方式:交换这两个 Widget 对象的值,我们实际要做的就是交换它们的 pImpl 指针
类型Widge完全特化标准模板:
当Widget和WidgetImpl是类模板,而不是类时怎么办?:
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); } }
相关文章推荐
- 条款25:考虑写出一个不抛异常的swap函数
- 《Effective C ++ 》资源管理:条款25--考虑写出一个不抛出异常的swap函数
- Effective C++:条款25:考虑写出一个不抛异常的swap函数
- 读书笔记《Effective C++》条款25:考虑写出一个不抛异常的swap函数
- 条款25:考虑写出一个不抛出异常的swap函数
- Effective C++ 条款25:考虑写出一个不抛异常的swap函数
- 《Effective C++》学习笔记条款25 考虑写出一个不抛异常的swap函数
- 《Effect C++》学习------条款25:考虑写出一个不抛出异常的swap函数
- 条款25:考虑写出一个不抛出异常的swap函数
- 《Effective C++》条款25:考虑写出一个不抛异常的swap函数
- effective C++ 条款 25:考虑写出一个不抛出异常的swap函数
- 条款25:考虑写出一个不抛异常的swap函数(Consider support for a non-throwing swap)
- 条款25 考虑写出一个不抛异常的swap函数
- 条款25:考虑写出一个不抛异常的swap函数
- 条款25 考虑写出一个不抛异常的swap函数
- Effective c++(第三版) 条款25:考虑写出一个不抛出异常的swap函数
- Effective C++:条款25:考虑写出一个不抛异常的swap函数
- [effectiv c++]条款25:考虑写出一个不抛出异常的swap函数(pimpl手法)
- 条款25:考虑写出一个不抛异常的swap函数
- Effective C++ -----条款25:考虑写出一个不抛异常的swap函数