Effective C++ 11. Handle assignment to self in operator=

来源:互联网 发布:网络测试工程师 编辑:程序博客网 时间:2024/06/06 13:25
class Widget {    ...private:    Bitmap *pb;};

不安全, 受自赋值影响

Widget& Widget::operator=(const Widget& rhs) {    delete pb; // unsafe, should avoid assignment to self    pb = new Bitmap(*rhs.pb);    return *this;}

还是不安全,如果申请内存失败将丢失原信息

Widget& Widget::operator=(const Widget& rhs) {    if (this == &rhs) return *this;    delete pb;     pb = new Bitmap(*rhs.pb);    return *this;}

改进后的两种方法
I.

Widget& Widget::operator=(const Widget& rhs) {    Bitmap *pOrig = pb;    pb = new Bitmap(*rhs.pb);    if (pb == NULL) //申请内存失败, 赋回原值        pb = pOrig;    else         delete pOrig;    return *this;}

II.

class Widget {    ...    void swap(Widget& rhs);    ...};
Widget& Widget::operator= (const Widget& rhs) {    Widget temp(rhs);    swap(tmp);    return *this;}
Widget& Widget::operator=(const Widget rhs) {    swap(rhs);    return *this;}
阅读全文
0 0
原创粉丝点击