
You're right. I'm mistaken. :) On Wed, May 7, 2008 at 11:11 AM, Scott McMurray <me22.ca+boost@gmail.com<me22.ca%2Bboost@gmail.com>> wrote:
On Tue, May 6, 2008 at 10:47 PM, shiwei xu <xushiweizh@gmail.com> wrote:
Your question is very interesting. I thought it before. In fact I don't know a perfect solution. If the constructor of an object throws, should the destructor be called?
class Foo { private: A m_a; B m_b; C m_c;
public: Foo() { m_a.init(); m_b.init(); thow std::exception("error"); m_c.init(); } ~Foo() { ... } };
Suppose we initialized m_a and m_b. m_c was uninitialized when the exception throws. If the destructor is called, it may cause a crash. If the destructor isn't called, the allocated memory of m_a and m_b will be leaked.
I choose to call the destructor because I think that a crash is easy to be detected and be solved.
This is a non-point. Go read the rules for which destructors are called when exceptions are thrown in different places. If A and B are written properly, there's no problem. And in any case, throwing in a constructor for an automatic variable doesn't call the destructor, so no matter what you think, you shouldn't call the destructor, since it'll break expectations.
Here's a simple counter-example: int *bar() { throw 0; return new int(42); } struct foo { int *p; foo() : p(bar()) {} ~foo() { delete p; } };
Quite obviously UB to call that destructor. _______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost