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

前端 未结 4 1800
温柔的废话
温柔的废话 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:43

    You could put it in the destructor of a class with a global instance.

    class SomeGlobalStuff {
        ~SomeGlobalStuff() {
              foo();
        }
        static SomeGlobalStuff instance;
    };
    // putting this in a single compilation unit.
    SomeGlobalStuff SomeGlobalStuff::instance instance;
    

    But like any other method, you have to remember that you cannot use any data if you cannot garantee that it still exists. Deallocation of global objects is done in a arbitrary order, so basically, you cannot use std::cout in the foo() function. atexit() is worse in this regard, because whether it executes before or after destruction of global objects depends on the compiler and compiler options.

    And anyway, you still have to handle signals correctly. You have to choose which signals to handle and which to not handle (you most likely don't want to handle SIGSEGV). You cannot escape signal handling. And remember that signals may interrupt your program at any time (unless masked) so your data structures might be in a arbitrary state, in the middle of an update.

提交回复
热议问题