条款11:在 operator= 中处理自我赋值
潜在的自我赋值以及危害
a[i] = a[j];
*px = *py;Widget& Widget::operator=(const Widget& rhs) {
delete pb;
pb = new Bitmap(*rhs.pb); // 如果是自我赋值,此时 *rhs.pb 指向的空间已经被释放;
return *this;
}解决办法
Widget& Widget::operator=(const Widget& rhs) {
if (this == &rhs) return *this; // 证同测试;
delete pb;
pb = new Bitmap(*rhs.pb);
return *this;
}Last updated