How do you run a function on exit in C++

前端 未结 4 1932
温柔的废话
温柔的废话 2021-02-05 10:27

I have a function that I want to run whenever my program exits:

void foo() {
  std::cout<< \"Exiting\" << std::endl;
}

How do I reg

4条回答
  •  难免孤独
    2021-02-05 10:39

    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.

提交回复
热议问题