Re: Exception in Constructor
On 2012-09-16 00:45, Henry wrote:
I am confused by the "note section" at
http://www.parashift.com/c++-faq/ctors-can-throw.html
It says, "if a constructor finishes by throwing an exception, the
memory associated with the object itself is cleaned up ? there is no
memory leak".
However, as I know (and I tested), when an exception is thrown
inside a constructor, the destructor won't be called.
Here is how I tested:
#include <iostream>
[...]
class A {
public:
A() {
m_b = new B(3);
throw 0;
}
~A() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
private:
B* m_b;
};
[...]
Inside A::A(), I new-ed B and then threw an exception on purpose,
and obviously, A::~A() and B::~B() weren't called.
It doesn't seems to me that "if a constructor finishes by throwing
an exception, the memory associated with the object itself is
cleaned up ? there is no memory leak" is true.
A::~A() is not called because the A object has never existed and
there's no A object to destroy, since the constructor of A "failed" by
throwing an exception. Only the subobject of A, A::m_b, had existed
and it is automatically destroyed by the (trivial) destructor of B*.
B::~B() is not called because the memory allocated by 'new', the B
object, is NOT "associated with the [A] object itself"; "the memory
associated with the [A] object itself" is the memory for A::m_b, the
B* object, the pointer itself, which IS correctly destroyed. And you
should understand that a pointer destroyed doesn't mean the memory
pointed to by the pointer reclaimed automatically, which is where a
smart pointer can be useful: a smart pointer object destroyed causes
the object pointed to by the pointer to be destroyed automatically, by
the action of the destructor of the smart pointer. So, there's no
memory leak for the A object itself (you don't need anything like
'delete this' or 'this->~A()'), but you're still responsible for
reclaiming extra resources allocated by 'new' or 'fopen', if any,
because they're not "the memory associated with the object itself".
You may find these articles enlightening:
http://www.gotw.ca/gotw/066.htm
http://www.gotw.ca/publications/mill13.htm
http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
--
Seungbeom Kim
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]