Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About operator=() from Meyers's book

Tags:

c++

I'm reading book by S. Meyers "Effective C++. 55 specific ways..." (3rd edition). And something in this book, in rule 11 I don't understand. So, in the next code part:

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

Why is "pOrig" used?

P.S. Sorry for my bad english.

like image 729
aaveNs Avatar asked Dec 14 '22 15:12

aaveNs


1 Answers

As you're dealing with raw pointers here, you have to do proper resource management. In in this case, there is a chance that new Bitmap(...) might throw, for example if the process is running out of memory, and it won't change the value of what pb points to because the exception would be triggered before the assignment takes place.

By introducing the temporary, you can still manage the Bitmap object correctly, because if the call to new succeeds, the old object does get deleted and you don't leak memory.

If you delete the object pointed to by pb first and the new Bitmap... code results in an exception, your object is in an internally messed up state.

Also, as Angew pointed out in the comments, by using the temporary to keep the internal state consistent, you also guard against self-assignment and can skip the self-assignment test as a side benefit.

like image 80
Timo Geusch Avatar answered Dec 29 '22 01:12

Timo Geusch