为什么没有std::on_exit
Why is there no std::on_exit?
程序可以使用各种不同的状态代码退出
我想绑定一个出口处理程序,作为基于此状态代码处理最终任务的一种捕获方式
是否可以从出口处理程序中调度状态代码
据我所知,没有。
因此,我无法获得状态值,如这个小示例所示:
#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世界中的交叉兼容性。
关于代码库:
我这样做的目标不涉及内存管理。我们有一个现有的代码库。到处都是退出声明。当程序出现错误退出时,我想显示错误代码对用户意味着什么。在我看来,这是没有重大重构的最快解决方案。
因为清理任务应该由析构函数执行,并且您的代码应该在任何情况下(通过return
或throw
)从任何范围优雅地返回。
at_exit
是RAII友好世界中的反模式。
如果您想根据将从main
返回的内容执行某些逻辑,只需在将从main
返回时执行即可。在main
。
最简单、最可移植的解决方案是将程序封装在shell脚本或其他程序中。然后,这个包装脚本或程序可以检查退出代码并向用户显示适当的消息。
相关文章:
- 瓦尔格林德:数学函数"Conditional jump or move depends on uninitialised value(s)"
- 循环挂起迭代的 std::擦除 on std::list
- SIGSEGV on Boost UDP 套接字关闭 - tcache_get at malloc.c.
- CPP 中的瓦尔格林德和记忆泄漏:"Conditional jump or move depends on uninitialised values"
- std::bind on statd::array 的运算符 []
- 您将如何连接"on the fly"文本+整数并将其传递给函数?
- 如何修复输出日志中的"EnableInput can only be specified on a Pawn for its Controller"错误
- 我如何测试代码没有调用 exit()
- VS2019 - Sudo Remote Debugging on Linux with Cmake project
- exit(0) 和 raise(SIGTERM) 有什么区别?
- "Program ended with exit code: 0"出现在我的输出的开头?
- C++ library with Tensorflow on Android
- SFML 交叉编译 for Windows on Linux.
- How to recover system gcc compiler on centos 6
- Cmake with Flex/Bison on windows
- 按原样保存用户输入 - Ruby on Rails
- OpenAL C++ on Linux
- Boost::process on Windows - with MinGW?
- CMake on FindOpenGL.cmake 中的错误,当使用导入的目标 OpenGL::GLU?
- Utilization of atomic_flag on C++