Why do I close the CMD window when debugging the program, and the destructor of the class object I create does not execute

xulu zhao 66 Reputation points
2022-04-28T09:07:56.207+00:00

197316-clipboard.png

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,411 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,520 questions
0 comments No comments
{count} votes

Accepted answer
  1. RLWA32 40,021 Reputation points
    2022-04-28T10:29:57.43+00:00

    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;
    }
    

0 additional answers

Sort by: Most helpful