为什么没有std :: on_exit?

Tre*_*key 4 c++ exit-code exit language-lawyer c++14

程序可以使用各种不同的状态代码退出.
我想将退出处理程序绑定为基于此状态代码处理最终任务的所有方法.
是否可以从退出处理程序中调度状态代码?
据我所知,.

因此,我无法获取状态值,如下面的小例子所示:

#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;
}
Run Code Online (Sandbox Code Playgroud)

有没有理由说C++还没有包含on_exit
我担心windows世界中的交叉兼容性.

关于代码库:
我这样做的目标,不涉及内存管理.我们有一个现有的代码库.到处都有退出声明.当程序退出时出错,我想显示该错误代码对用户的意义.在我看来,这是没有重大重构的最快解决方案.

Lig*_*ica 10

因为清理任务应该由析构函数执行,并且您的代码应该在任何情况下(无论是通过return还是throw)优雅地从任何作用域返回.

at_exit 在RAII友好的世界中是一种反模式.

如果您想根据要返回的内容执行某些逻辑main,只需在您即将返回时执行main.在main.


Joh*_*ela 0

最简单、最可移植的解决方案是将您的程序包装在 shell 脚本或其他程序中。然后,该包装脚本或程序可以检查退出代码并向用户显示适当的消息。