Registering a function to be called when a program exits normally
It is common that a program, upon exit, must clean up code to release resources, write something to a log, or do some other end operation. The standard library provides two utility functions that enable us to register functions to be called when a program terminates normally, either by returning from main()
or through a call to std::exit()
or std::quick_exit()
. This is particularly useful for libraries that need to perform an action before the program is terminated, without relying on the user to explicitly call an end function. In this recipe, you will learn how to install exit handlers and how they work..
Getting ready
All the functions discussed in this recipe, exit()
, quick_exit()
, atexit()
, and at_quick_exit()
, are available in the namespace std
in the header <cstdlib>
.
How to do it...
To register functions to be called upon termination of a program, you should use the following:
...