In C++, are global objects guaranteed to exist throughout the execution of a SetConsoleCtrlHandler() callback function?

Geoff Hale 0 Reputation points
2025-02-05T01:22:18.9666667+00:00

In C++, are global objects guaranteed to exist throughout the execution of a SetConsoleCtrlHandler() callback function?

I'm wondering what would happen if both regular program execution (and the eventual destruction of global variables) and the HandlerRoutine() are racing to complete.

The reason I ask is that my HandlerRoutine() needs to use some global objects, though I'm not sure if they would still exist if regular program termination ended up completing before an invoked HandlerRoutine() call.

I haven't had any problems, though I'm not sure if this is guaranteed.

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,736 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,857 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Darran Rowe 1,426 Reputation points
    2025-02-05T02:16:16.6066667+00:00

    Globals are guaranteed to exist from the moment the code enters main/wmain/WinMain/wWinMain/DllMain and are guaranteed to exist until the code exits the main function.

    While it isn't accurate, the startup code essentially does:

    void execute_main()
    {
        //Other stuff
        initialise_globals();
        invoke_main();
        cleanup_globals();
        exit();
    }
    

    If there is a major concern that the handler may use something that gets destroyed, use SetConsoleCtlHandler again just before the main funtion returns to remove the handler. Passing in the same pointer to the handler function as was used when the handler was registered, but use FALSE for the second parameter should remove the handler.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.