I am reading this book and I do not understand the difference between two pieces of code.
class Bitmap{...};
class Widget
{
...
private:
Bitmap* m_pb;
};
Widget& Widget::operator=(const Widget& rhs)
{
if (this == &rhs)
{
return *this; // if a self-assignment, do nothing
}
delete pb;
pb = new Bitmap(*rhs.m_pb);
return *this;
}
Mr. Meyers says:
if the "new Bitmap" expression yields an exception, the Widget will end up holding a pointer to a deleted Bitmap.
Does it mean that the pd pointer points to NULL?
Widget& Widget::operator=(const Widget& rhs)
{
Bitmap* temp = pb;
pb = new Bitmap(*rhs.pb);
delete temp;
return *this;
}
Mr. Meyers says:
Now, if "new Bitmap" throws an exception, pb pointer remains unchanged.
As far as I know, temp pointer points to the same memory address as pb pointer. If the "new" throws an exception, pb will point to NULL and the next sentence will delete the Bitmap. Is that correct? I do not see the difference between these implementations.
Thanks in advance.
The fact that you assign
tempto the same memory location aspbdoesn't influencepbin any manner. In the next line, ifBitmapconstructor will throw an exception the control won't reach the assignment part, thuspbwill remain unchanged.