C++箴言:在operator= 中處理自賦值
http://www.builder.com.cn/2007/1027/585438.shtml
w = w;
自賦值安全(self-assignment-safe)
異常安全(exception-safe)
=================================================================
Widget&
Widget::operator=(const Widget& rhs) // unsafe impl. of operator=
{
delete pb; // stop using current bitmap
pb = new Bitmap(*rhs.pb); // start using a copy of rhs's bitmap
return *this; // see Item 10
}
class Widget {
...
void swap(Widget& rhs); // exchange *this's and rhs's data;
... // see Item 29 for details
};
================================================================
Widget& Widget::operator=(const Widget& rhs)
{
Widget temp(rhs); // make a copy of rhs's data
swap(temp); // swap *this's data with the copy's
return *this;
}
沒有留言:
張貼留言