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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With