【发布时间】:2016-04-15 15:14:26
【问题描述】:
程序可以以各种不同的状态码退出。
我想绑定一个退出处理程序,作为基于此状态代码处理最终任务的全部方法。
是否可以从退出处理程序中调度状态代码?
据我所知,No。
因此,我无法获取状态值,如这个小例子所示:
#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;
}
C++ 还没有包含on_exit 有什么原因吗?
我担心 windows 世界的交叉兼容性。
关于代码库:
我这样做的目标不涉及内存管理。我们有一个现有的代码库。到处都有退出语句。当程序因错误退出时,我想显示该错误代码对用户意味着什么。在我看来,这是无需重大重构的最快解决方案。
【问题讨论】:
-
因为不需要?您现在可以做同样的事情,只需将您的代码包装在
try/catch/finally块中。当语言没有异常处理时,需要退出处理程序 -
您可以自己实现
exit(),覆盖标准库版本,并在对数字代码执行任何操作后调用_exit()。我不确定这是一个好主意,但如果你真的必须这样做,它可能是一种获得你想要的东西的方法。 -
@PanagiotisKanavos 只需
try-catch,C++ 中不需要finally。 -
@juanchopanza 您无法捕获已经存在的退出语句。不过我同意,例外通常是更好的途径。
标签: c++ language-lawyer c++14 exit exit-code