effective第11个条款举的这个例子:
Widget& Widget::operator=(const Widget& rhs) //一份不安全的operator=实现版本
{
delete pb;
pb = new Bitmap(*rhs.pb);
return *this;
}
像上面这样写,自我赋值肯定会出现问题,但是为什么要先释放掉pb呢?为什么不直接像下面这样重赋值呢?
Widget& Widget::operator=(const Widget& rhs) //一份不安全的operator=实现版本
{
pb = new Bitmap(*rhs.pb);
return *this;
}
The second way of writing will cause memory leaks when copying itself
The role of pb is to bind between referenced values and memory objects on the heap. If you want to access objects on the heap, you need to operate through pb.
See the picture above. According to the example you gave, you instructed pb to point to a new heap memory address, but you did not delete it before, which will cause a memory leak.
An example of a leak