在使用=
是,我们可能遇到以下这种自己赋值给自己的情况
class Widget{---};
Widget w;
...
w = w;
- 假定我们对
=
有以下的实现
class Bitmap {...};
class Widget{
...
Widget& operator=(const Widget& rhs) {
delete pb;
pb = new Bitmap(*rhs.pb);
return *this;
}
private:
Bitmap *pb;
};
以上实现在遇到w = w
自身赋值给自身(self-assignment-unsafe)的情况会出现错误,最后pb
指向一个被delete
的对象。
- 针对self-assignment-unsafe的问题,我们改进为如下
class Bitmap {...};
class Widget{
...
Widget& operator=(const Widget& rhs) {
if (this == &rhs) return *thsi;
delete pb;
pb = new Bitmap(*rhs.pb);
return *this;
}
private:
Bitmap *pb;
};
以上实现解决了w = w
的问题,但是依旧存在exception-unsafe的问题。因为在进行new
操作的时候可能会出现exception,这可能会导致pb
指向一个delete
的对象。
- 针对exception-unsafe的问题,我们改进如下
class Bitmap {...};
class Widget{
...
Widget& operator=(const Widget& rhs) {
Bitmap *pOrig = pb;
pb = new Bitmap(*rhs.pb);
delete pOrig;
return *this;
}
private:
Bitmap *pb;
};
- 同样的为了消除self-assignment-unsafe和exception-unsafe的问题,我们可以使用copy and swap的方法
class Bitmap {...};
class Widget{
...
void swap(Widget& rhs);
Widget& operator=(const Widget& rhs) {
Widget temp(rhs);
swap(temp);
return *this;
}
// or
Widget& operator=(Widget rhs) {
swap(rhs);
return *this;
}
private:
Bitmap *pb;
};
对于以上的实现,并没有进行传入的参数是否自身的判断,因为考虑到效率方面的问题,引入判断之后会带来分支,影响性能。并且在正常使用的情况下,一般都不会出现传入参数为自身的情况,所以以上为了性能,没有加入判断是否为自身的if
语句。