为什么没有std::on_exit

Why is there no std::on_exit?

本文关键字:on exit std 为什么      更新时间:2023-10-16

程序可以使用各种不同的状态代码退出
我想绑定一个出口处理程序,作为基于此状态代码处理最终任务的一种捕获方式
是否可以从出口处理程序中调度状态代码
据我所知,没有。

因此,我无法获得状态值,如这个小示例所示:

#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 failedn";
      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 successn";
      return EXIT_SUCCESS;
    }
    std::cout << "exiting with failuren";
    return EXIT_FAILURE;
}

C++还没有包含on_exit是有原因的吗
我担心windows世界中的交叉兼容性。

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

因为清理任务应该由析构函数执行,并且您的代码应该在任何情况下(通过returnthrow)从任何范围优雅地返回。

at_exit是RAII友好世界中的反模式。

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

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