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.
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.
Share Improve this question edited Jan 31 at 18:18 Remy Lebeau 598k36 gold badges503 silver badges848 bronze badges asked Jan 31 at 17:37 uncreateuncreate 534 bronze badges 7 | Show 2 more comments1 Answer
Reset to default 0No, they are not. That is if you mean in terms of object lifetime.
Windows starts a new thread to run your console handler routine on, and it's possible that at that moment main
has already finished, and the runtime is in process of executing global destructors. If some of those destructors hangs or deadlocks, and the user presses Ctrl+C in attempt to terminate, then yes, you cannot guarantee which of your global objects are destroyed and which are not.
That said, the allocated address space is still there, and accessing simple variables won't crash.
main()
(orWinMain()
?) and destroyed aftermain()
returns. So, if you callback is called bymain()
(or a function it calls, directly or indirectly) the global will exist. You will only have concerns if the callback is called by constructor or destructor of a global object (look up static initialisation order fiasco). – Peter Commented Jan 31 at 17:51