自我赋值发生在自己赋值给自己时:
class Widget{...};
Widget w;
w = w;
或者:
a[i] = a[j];
*px = *py;
假如你建立一个class来保存一个指针指向一块动态分配的位图(bitmap):
class Bitmap{...};
class Widget {
...
private* pb; 指针,指向一个从堆中分配得到的对象
};
operator= 实现
Widget&
Widget::operator=(const Widget& rhs)
{
delete pb; // 释放当前的bitmap
pb = new Bitmap(*rhs.pb); // 使用rhs的bitmap副本
return *this;
};
这个代码如果 rhs 就是 自己,就会导致new Bitmap的时候出现异常行为。所以保险起见要判断是否出现自我赋值
Widget&
Widget::operator=(const Widget& rhs)
{
if (&rhs == this) return *this;
delete pb; // 释放当前的bitmap
pb = new Bitmap(*rhs.pb); // 使用rhs的bitmap副本
return *this;
};