Reputation: 27375
I'm reading Scott Meyers' Effective C++ and he provided an example of a well-designed assignement operator. Here it is:
class Bitmap{ ... };
class Widget
{
//...
private:
Bitmap *pb;
};
Widget::operator=(const Widget& rhs)
{
Bitmap *pOrig = pb;
pb = new Bitmap(*rhs.pb);
delete pOrig;
return *this;
}
Now, the explanation he gives right after the example is about how the code is exception-safe.
Now, if
new Bitmap
throws an exception, pb (and the Widget it's inside of) remains unchaged)
I don't understand that. How can we ever talk about unchanging here if throwing execeptions by a constructor leads us to UB (because operator delete
will no be called on the pointer return by the new
operator which results in an exception) ?
Upvotes: 0
Views: 80
Reputation: 179779
If a constructor throws, operator new
will not keep the memory allocated. This prevents the memory leak.
Note that a memory leak wouldn't be Undefined Behavior.
Upvotes: 2