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

C++使用技巧:copy and swap idiom

2012-11-20 19:58 441 查看
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概念(局部变量退出作用域时触发析构函数),解决了自身赋值,强异常保证。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: