0

Possible Duplicate:
Is the destructor called if the constructor throws an exception?

I have a question to you. Does destructor is executed, when constructor throws an exception? Sample code:

#include <cstdio>

struct Test
{
    Test (void)
    {
        throw 100;
    }

    ~Test (void)
    {
        printf ("~Test\n");
    }
};

int main (void)
{
    try
    {
        Test test;
    }
    catch (int value)
    {

    }
}

When running this code "~Test" is not displayed. Ok, I may understand this behavior. Assume that Test have dynamically allocated members, which are allocated inside constructor and deleted in destructor. What will happen with them, when exceptions is thrown after they were allocated in constructor?

Community
  • 1
  • 1
Goofy
  • 5,187
  • 5
  • 40
  • 56
  • Yet another reason not to have dynamically allocated members. If you really have to use dynamically allocated members then wrapping each of those members in their own class will solve this problem. Since they will then be fully constructed and their own destructors will be called. – john Nov 08 '12 at 11:23

3 Answers3

2

Only destructors of fully constructed objects are called during stack unwinding. If your constructor throws after it already dynamically allocated some memory, the destructor will not be called and you'll leak it (assuming you used raw new, that is).

Destructors of members that were successfully constructed by the time the expection was thrown do get called, though. If instead of raw new you use a smart pointer or container, the resources will be properly cleaned up.

jrok
  • 54,456
  • 9
  • 109
  • 141
0

No the destructor does not get executed. However the destructor for any member variables that have been sucessfully constructed will be executed.

jcoder
  • 29,554
  • 19
  • 87
  • 130
0

There is a very detailed answer on this (and possible ways to do proper resource management in such a case) in Is the destructor called if the constructor throws an exception?

Community
  • 1
  • 1
sim82
  • 88
  • 4