According to the FAQ, the best way to inform a class user of an error
that occurs inside a constructor is to throw an exception. My question
is, what happens when an object is instantiated using 'new', and the
constructor throws after 'new' allocates memory for that object? Will
the memory leak? Thanks.
the memory is freed automatically. This is easy to check.
Using exceptions to terminate constructors is very elegant.
Think about the horrible solutions people invented before exceptions
were introduced.
Now you can have a fallible resource allocation inside a constructor.
Some suggestions:
* perform only a single resource allocation inside a constructor.
If you perform more than one allocation inside a constructor you will
have to deal with cleanup yourself in case of one of the allocation
fails. Remember that destructors are only called for successfully
constructed objects (which have not been aborted by a exception
thrown). If you throw in a constructor of a class which has base-
classes or member-classes, the destructors for the successfully
constructed base-classes or member-classes are called.
* resource allocation is everything which is paired:
Creating a window/destroying a window
Opening a file/closing a file
mapping a file/unmapping a file
setting a handler/restoring the original handler
showing a window/hiding a window
creating a (bitmap) handle, destroying this (bitmap) handle
* throw an exception if the matching allocation fails. This exception
should contain all necessary information -- e.g. system error
information to give rich error information
* chain such single allocation classes into more complex classes using
base-class/member class relationships