Copy and Swap idiom
使用到著名的Big three中兩個特殊的成員函數(拷貝構造函數copy construction與賦值構造函數assignment constrcution). 作用在于在深拷贝的过程中保证强异常的作用,具体代码如下
class Person { public: Person(int id, const char * pszName):_id(id), _pszName(new char[strlen(pszName) + 1]){strcpy(_pszName, pszName);} Person():_id(0) { _pszName = new char[1]; _pszName[0] = '\0'; } ~Person() { if (_pszName) delete _pszName; _pszName = nullptr; } int Id(void) const {return _id;} const char * Name(void) const {return _pszName;} Person(Person& rhs) { _id = rhs._id; _pszName = new char[strlen(rhs._pszName) + 1]; strcpy(_pszName, rhs._pszName); } Person& operator=(Person& rhs) { Swap(rhs); return *this; } private: void Swap(Person rhs) { std::swap(_id, rhs._id); std::swap(_pszName, rhs._pszName); } private: int _id; char * _pszName; };这里使用了RAII概念(局部变量退出作用域时触发析构函数),解决了自身赋值,强异常保证。