author:
- luixiao1223
title: 在operator=中处理自我赋值
常规做法
Widget& Widget::operator=(const Widget& rhs)
{
if (this == &rhs) return *this;
delete pb;
pb = new Bitmap(*rhs.pb);
return *this;
}
缺点:这里在new Bitmap的时候没有异常处理
如果删除pb之后,new失败。那么最后pb将指向被删除的区域
copy and swap技术
class Widget {
void swap(Widget& rhs);
Widget& Widget::operator=(const Widget& rhs) {
Widget temp(rhs);
swap(temp);
return *this;
}
};
Widget& Widget::operator=(Widget rhs) { //传值,自动生成临时变量。
swap(rhs);
return *this;
}
//拷贝副本牺牲效率。但是自我赋值其实很少发生。所以不用考虑自我赋值造成的问题。