One question about your sample. If not using smart pointer, and if at
the
same time, the construction of m_Whatever is successful, but the
construction
of current instance is failed and exception is thrown -- throw
SomeException();
then, I think there will be memory leak since delete n_Whatever is not
invoked explicitly?
BTW: if the caller of the constructor MyClass() is smart enough, it
will
catch the exception and delete the member m_Whatever? Is that
possible?
The canonical example:
class MyClass
{
public:
MyClass() : m_Whatever(new Whatever)
{
// m_Whatever's destructor is still called
throw SomeException();
}
private:
std::auto_ptr<Whatever> m_Whatever;
};
The rule is that a destructor will be called only if its constructor
completed successfully. Note that we have two objects here however,
"MyClass" which someone will instantiate, and "m_Whatever" which is
created just before the body of the "MyClass" constructor starts
running.
Each of these objects has its own constructor. Note that by the time
the
body of the "MyClass" constructor starts running however, "m_Whatever"
has
already been fully created and initialized with a pointer to "Whatever"
(which it encapsulats internally). Its destructor is then guaranteed to
run based on my opening statement of this paragraph. Moreover, based on
the very same statement, when "SomeException" is thrown, the "MyClass"
constructor hasn't finished running so its destructor will *not* be
called
(though I haven't explicitly defined one). Only the destructor for
"m_Whatever" is called as noted and that automatically deletes
"Whatever".
You therefore have nothing to do to clean things up yourself. Just
catch
"SomeException" to handle the error and that's it.
of type Whatever and avoid the pointer completely.