Why is there no std::on_exit?

时间:2016-04-15 15:14:27

标签: c++ language-lawyer c++14 exit exit-code

A program can exit with a variety of different status codes.
I'd like to bind an exit handler as a catch all way of handling final tasks based on this status code.
Is it possible to dispatch on the status code from within the exit handler?
As far as I can tell, No.

Therefore, I am unable to obtain the status value, as shown in this small example:

#include <iostream>
#include <cstdlib>

int Get_Return_Code(){
  //can this be implemented?
  return 0;
}

void Exit_Handler() {

    // how do I get the return code
    // from within the exit heandler?
    auto return_code = Get_Return_Code(); //?

    // I'd like to make decisions based on the return code
    // while inside my exit handler
    if (return_code == EXIT_SUCCESS){
      std::cout << "perform exit successful tasks...\n";
    }
    else {
      std::cout << "perform exit failure tasks...\n";
    }
}

int main(int argc,  char** argv) 
{
    //bind the exit handler routine
    if (std::atexit(Exit_Handler)){
      std::cerr << "Registration failed\n";
      return EXIT_FAILURE;
    }

    //if an argument is passed, exit with success
    //if no argument is passed, exit with failure
    if (argc > 1){
      std::cout << "exiting with success\n";
      return EXIT_SUCCESS;
    }

    std::cout << "exiting with failure\n";
    return EXIT_FAILURE;
}

Is there a reason that C++ does not yet include on_exit?
I'm concerned about cross-compatibility in the windows world.

in regards to the code base:
My goal for doing this, does not involve memory management. We have an existing code base. There are exit statements everywhere. When a program exits with error, I'd like to display what that error code means to the user. In my mind, this is the fastest solution without major refactoring.

2 个答案:

答案 0 :(得分:10)

Because cleanup tasks are supposed to be performed by your destructors, and your code is supposed to gracefully return from any scope under all circumstances (be it via return or throw).

at_exit is an anti-pattern in a RAII-friendly world.

If you want to perform some logic depending on what you're about to return from main, simply perform it when you're about to return from main. In main.

答案 1 :(得分:1)

最简单,最便携的解决方案是将程序包装在shell脚本或其他程序中。然后,此包装脚本或程序可以检查退出代码并向用户显示相应的消息。