The destructor isn't called in unexpected program termination?

Hi guys.

I have a doubt...

The destructor is called when for example I click in the (X) button to close?
Is called when I do a taskkill?

See that code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
using namespace std;

class foo
{
	public:
		int* alloc;

		foo()
		{
			alloc = new int[1000];
		}

		~foo()
		{
			delete [] alloc;
			cout << "\nDestructor called\n";
			cin.get();
		}

};


int main()
{
	foo Bar;
	cout << "Please press ENTER instead of close the window, otherwise will create a leak";

	cin.get();

	return 0;
}



If the program closes appropriately the output is:

Please press ENTER instead of close the window, otherwise will create a leak
[pause]

Destructor called

[pause]


Okay, deleted the pointer, good.

But, if I close the console window instead of press enter:

Please press ENTER instead of close the window, otherwise will create a leak
[pause]


The destructor wasn't called?
Leak?
Last edited on
I think the behaviour of closing the console windows depends on your OS. I think the most common is to just kill the program and not run destructors and such. You don't have to worry about the leak. The OS will clean up all memory after the program has terminated.
Last edited on
How do you check if your destructor is called exactly? You call your program by the console but you close the console so you never see output I guess.

Anyway usually when a program is terminated all it's allocated memory is returned to the OS. The problem is when it's not terminated but instead sleeps or something. Then you may have a problem.
There could be resources that the OS doesn't recover on unexpected progam termination
(SysV shared memory is one)

You can define your own terminate handler

http://www.cplusplus.com/reference/std/exception/set_terminate/

I've never used this
Last edited on
Thanks for the answers! I get it.
Topic archived. No new replies allowed.