Exception in Constructor
{ Please limit your text to fit within 80 columns, preferably around 70,
so that readers don't have to scroll horizontally to read each line.
This article has been reformatted manually by the moderator. -mod }
Hi,
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 B {
public:
int m_x;
B(int x) : m_x(x) {}
~B() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
class A {
public:
A() {
m_b = new B(3);
throw 0;
}
~A() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
private:
B* m_b;
};
int main() {
try {
A a;
}
catch (...) {
std::cout << "caught an exception :)" << std::endl;
}
return 0;
}
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.
I am pretty certain that I interpret it incorrectly. Can someone elaborate?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]