The destructor is not called when an exception is thrown

Consider the following code:

#include <iostream> using namespace std; class Test { static int count; int id; public: Test() { count++; id = count; cout << "Constructing object number " << id << endl; if(id == 4) throw 4; } ~Test() { cout << "Destructing object number " << id << endl; } }; int Test::count = 0; int main() { try { Test array[5]; } catch(int i) { cout << "Caught " << i << endl; } } 

The above code produces the following output:

 Constructing object number 1 Constructing object number 2 Constructing object number 3 Constructing object number 4 Destructing object number 3 Destructing object number 2 Destructing object number 1 Caught 4 

I thought that destructors are always called when objects become inaccessible, even when exceptions are thrown. Why in this case Test instance destructors are not called?

+6
source share
2 answers

You create an array of 5 Test objects, but you throw an exception after creating 3 complete objects. An exception is thrown when in the constructor 4 4th object. Building a 4 th object is not complete until the final bracket of the constructor is reached.

The stack unpacks the call to the destructor for those 3 fully constructed objects in the opposite order in which they were created, since objects 4 th and 5 th were never constructed, the destructor for them is never called.

The rule for exclusion is:
After an exception is thrown by destructors for all fully created objects inside this area, it will be called.
A fully created object is one whose constructor is called purely without any exceptions.

+8
source

Instead of writing the cout statement after id = count, as follows: -

  id = count; cout << "Constructing object number " << id << endl; if(id == 4) throw 4; 

you should have written it after the throw statement. That would give you the best thing that happened. Like this: -

 Test() { count++; id = count; if(id == 4) throw 4; cout << "Constructing object number " << id << endl; } 

O / r would be: - Building facility number 1 Building facility number 2 Building facility number 3 Destruction of facility number 3 Destruction of facility number 2 Destruction of facility number 1 Captured 4

+3
source

Source: https://habr.com/ru/post/907090/


All Articles