effective c++:写出一个不抛出异常的swap函数

xiaoxiao2021-02-28  114

考虑写出一个不抛出异常的swap函数

假设Widget和WidgetImpl都是class:

class WidgetImpl{ //针对Widget数据而设计的class public:   ... private:   int a,b,c; //可能很多数据   std::vector<double>v; //意味复制时间很长 };

当Widget被置换时真正该做的是置换内部指针,可以将std::swap针对Widget特化。

class Wigdet{ //这个class使用pimpl手法 public:   Widget(const Widget& rhs);   void swap(Widget& other){   using std::swap;   swap(pImpl,other.pImpl);   } private:   WidgetImpl* pImpl; //指针,所含对象内含WIdget数据 }; namespace std{   template<>   void swap<Widget>(Widget& a,Widget& b){   a.swap(b);   } }

这种做法与stl容器有一致性。

假设Widget和WidgetImpl都是class template:

template<typename T> class WidgetImpl{...}; template<typename T>class Widget{...}; namespace std{   template<typename T>   void swap<Widget<T>>(Widget<T>& a,Widget<T>& b){   a.swap(b);   } }

此不合法,企图偏特化一个function template,c++只允许对class template偏特化。也不允许添加新的template到std里头。

改进:

namespace WidgetStuff{   ...   template<typename T>   class Widget{}; //同前,内含swap成员函数   ...   template<typename T>   void swap(Widget<T>& a,Widget<T>& b){   a.swap(b);   } } template<typename T> void doSomething(T& obj1,T& obj2){   using std::swap; //令std::swap在此函数可用   ...   swap(obj1,obj2); //为T型对象调用最佳swap版本   ... }

转载请注明原文地址: https://www.6miu.com/read-49686.html

最新回复(0)