I have a function that I want to run whenever my program exits:
void foo() {
std::cout<< \"Exiting\" << std::endl;
}
How do I reg
You can use the aptly named std::atexit function in the cstdlib
header:
#include
void exiting() {
std::cout << "Exiting";
}
int main() {
std::atexit(exiting);
}
The system will maintain a stack of functions registered with atexit
and call them each in the reverse order of their registration when either the exit
function is called, or the program returns from main
. You can register at least 32 functions this way.