2,783 questions
The destructor does not run because when the close button of a console window is clicked the system terminates the console process. This is not a normal termination.
You can see this by running the following sample code. It adds an atexit function that only runs on normal termination. It also adds a handler for console application events. When debugging observe the messages directed to the Output pane. You can see the difference between a normal termination and how the system otherwise terminates the process.
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>
#include <tchar.h>
class Log
{
public:
Log()
{
OutputDebugStringA("In Log Constructor\n");
}
~Log()
{
OutputDebugStringA("In Log Destructor\n");
}
};
void NormalTermination(void)
{
OutputDebugStringA("Normal Termination\n");
}
BOOL CALLBACK Handler(DWORD CtrlType)
{
switch (CtrlType)
{
case CTRL_C_EVENT:
OutputDebugStringA("Ctrl-C\n");
return FALSE;
case CTRL_BREAK_EVENT:
OutputDebugStringA("Ctrl-Break\n");
return FALSE;
case CTRL_CLOSE_EVENT:
OutputDebugStringA("Ctrl-Close\n");
return FALSE;
case CTRL_LOGOFF_EVENT:
OutputDebugStringA("Ctrl_Logoff\n");
return FALSE;
case CTRL_SHUTDOWN_EVENT:
OutputDebugStringA("Ctrl-Shutdown\n");
return FALSE;
default:
OutputDebugStringA("We shouldn't be here\n");
return FALSE;
}
}
int main()
{
Log l;
SetConsoleCtrlHandler(Handler, TRUE);
atexit(NormalTermination);
printf("Close Console Window now or hit enter to exit\n");
_getch();
return 0;
}