Calling class destructor if program killed

Mar 9, 2009 at 9:13pm
It's me again :D

I've really been experimenting with C++ over the last week or two, and I just wondered if you could call a class's destructor just before a program was killed. I tried it with this (which I suspected wouldn't work - and sure enough, it didn't):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

class TerminationTest {
public:
    TerminationTest() {cout << "Termination test started. Please press CTRL+C to terminate this program." << endl;}
    ~TerminationTest() {cout << "Terminated safely." << endl;}
} test;

int main()
{
    while (true);
    return 0;
}


Output:

$ g++ ./term.cpp -o ./term
$ ./term
Termination test started. Please press CTRL+C to terminate this program.
^C
$


So is there a (preferably simple to understand - I'm only a beginner!) way to do this?

Thanks in advance.
Mar 9, 2009 at 10:06pm
dtors are called automatically when the object dies. This happens when it is deleted (if it was allocated with new), or when it loses scope (if it was declared locally), or when the program closes (if it was global).

In the above example... the dtor will be called when the program closes because test is global. however this is bad practice because you're using cout in the dtor which is also global -- and it's possible cout has been deleted before your class has. So you should refrain from making objects like this global.

Another reason you not getting the dtor message is because you're deadlocking in an infinite loop while(true);. Which means the program never closes, which means the dtor is never called.

Some other things you can try:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class TerminationTest
{
//...
};  // do not make the global "test" object

void SomeFunc()
{
  TerminationTest a;  // a's ctor called here
}  // a's dtor called here

int main()
{
  TerminationTest* b = new TerminationTest;  // b's ctor called here
  SomeFunc();
  delete b;  // b's dtor called here

  return 0;
}
Last edited on Mar 9, 2009 at 10:09pm
Mar 9, 2009 at 10:59pm
But the question is: if the user presses Ctrl-C, does the OS abruptly kill the app or allow it to exit gracefully? I'm thinking the former.

Mar 9, 2009 at 11:55pm
You could try testing it by writing to a file inside a dummy class destructor, then ctrl+c-ing it.
Topic archived. No new replies allowed.