Stop execution without missing destructors

Is it possible to complete software execution without missing calls to destructors? For example, in the code below, the destructor for test will never be called due to the exit(1) statement.

 #include <iostream> #include <cstdlib> using namespace std; class A{ public: A(){cout << "Constructed.\n";} ~A(){cout << "Destroyed.\n";} }; void func() { //Assuming something went wrong: exit(1); } int main(int argc, char *argv[]) { A test; func(); return 0; } 

What I need is a way to end the program (from inside func() ), which calls all the necessary destructors before exiting. So far, I have been handling this through the func() return value, as in:

 bool func() { //Assuming something went wrong: return false; } int main(int argc, char *argv[]) { A test; if( !func() )return 1; return 0; } 

The problem with this method is that it quickly becomes very annoying (and the code swells) to control when you need to apply it to a series of nested functions.

Is there a way to achieve the same results of the second example (correct calls to the destructor) with syntax similar to the first example (calling exit(1) wherever you are)?

+7
source share
4 answers

Throw an exception, catch it in main and return.

It does not depend on the fact that you will not catch your exception without solving it.

+9
source

You can rely on the promotion of the stack for this: when you want to exit, throw an exception and catch it in main() .

+5
source
 struct my_exit { int error; int operator()() { // do any cleanup on globals return error; } }; int main() { try { doSomethingThatCouldCauseExit(); } catch (my_exit & me) { // Clean up globals now exit(me()); } } 
+1
source

There are several ways to do this cleanly.

One solution is to use the atexit function, which simply calls the specified function pointer when the program terminates.

You will need to select all your objects from the heap, save some global table with pointers to all instances of the instance instances, and then just iterate over the delete table of each instance in the registered function.

0
source

All Articles