class Widget {
public:
Widget(int x=0): val(new int(x)) {}
~Widget() { delete val; }
Widget(const Widget &rhs): val(new int(*rhs.val)) {}
//operator =
Widget& operator=(const Widget &rhs);
void print() const { cout << *val << endl; }
private:
int *val;
};/** wrong version
* not-safe when self-assignment occurs.
*/
Widget& Widget::operator=(const Widget &rhs) {
delete val;
val = new int(*rhs.val);
return *this;
}Widget& Widget::operator=(const Widget &rhs) {
if(this == &rhs) return;
delete val;
val = new int(*rhs.val);
return *this;
}Widget& Widget::operator=(const Widget &rhs) {
int *pOld = val;
val = new int(*rhs.val);
delete pOld;
return *this;
}Widget& Widget::operator=(const Widget &rhs) {
Widget temp(rhs);
swap(temp);
return *this;
}Widget& Widget::operator=(Widget rhs) { //yes, copy by value
swap(rhs);
return *this;
}operator=处理自我赋值,布布扣,bubuko.com
原文:http://blog.csdn.net/shoulinjun/article/details/36212035