条款11:在operator=中处理自我赋值

别在停止使用资源前释放它

class Bitmap
{
};
class Widget
{
public:
    Widget()
    {
        pb = NULL;
    }
    Bitmap *pb ;
    Widget& operator=(const Widget&);
};

Widget& Widget::operator=(const Widget& rhs)
{
    delete pb;
    pb = new Bitmap(*rhs.pb);
    return *this;
}
Widget a, b;
a = b;
/*
上述a=b进行赋值是有问题的,因为operator=函数内
*this和rhs有可能是同一个,所以在delete pb时
有可能把当前对象的bitmap和rhs的bitmap都删除了,
这时候pb就指向已被删除的对象
*/
Widget& Widget::operator=(const Widget& rhs)
{
    Bitmap* pOrig = pb;
    pb = new Bitmap(*rhs.pb);
    delete pOrig;
    return *this;
}
/*
上述operator=函数中先用pOrig记住原先的pb,
然后用pb指向*pb的一个副本,
最后删除pOrig(就是原来的pb)
*/
发布了96 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/L_H_L/article/details/78072978