1. 证同测试(保证自我复制安全)
传统做法是藉由operator一最前面的一个“证同测试(identity test)达到“自我赋值”的检验目的:
Widget& Widget::operator=(const Widget& rhs)
{
if (this==&rhs) return *this; //证同测试(identity test): 如果是自我赋值,就不做任何事。
delete pb;
pb = new Bitmap(*rhs.pb);
return *this;
}
2. 保证自我复制安全和异常安全的实现
widget& Widget::operator=(const Widget& rhs)
{
Bitmap* pOrig一pb; //记住原先的pb
pb二new Bitmap(*rhs.pb);//令pb指向*pb的一个复件(副本)
delete pOrig;//删除原先的pb
return *this;
}
3. copy and swap技术
class Widget
{
void swap(Widget& rhs);//交换‘this和rhs的数据;详见条款29
};
Widget& Widget::operator=(const Widget& rhs)
{
widget temp(rhs); //为rhs数据制作一份复件(副本)
swap (temp); //将*this数据和上述复件的数据交换。
return *this;
}
4. 总结
1)确保当对象自我赋值时operator=有良好行为。其中技术包括比较“来源对象”和“目标对象”的地址、精心周到的语句顺序、以及copy-and-swap。
2)确定任何函数如果操作一个以上的对象,而其中多个对象是同一个对象时,其行为仍然正确。