本文介绍了什么时候是C ++终止处理程序Right Thing(TM)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准提供了 std :: set_terminate 函数,它允许您指定什么函数 std :: terminate 应该实际上叫。 std :: terminate 只能在极端情况下被调用,并且当标准描述的时候,被称为是可怕的(例如未捕获的异常)。当 std :: terminate 确实被称为情况似乎是不符合内存的情况 - 你没有太多的理由可以做。

The C++ standard provides the std::set_terminate function which lets you specify what function std::terminate should actually call. std::terminate should only get called in dire circumstances, and sure enough the situations the standard describes for when it's called are dire (e.g. an uncaught exception). When std::terminate does get called the situation seems analagous to being out of memory -- there's not really much you can sensibly do.

我已经看到它可以用来确保资源被释放 - 但是对于大多数资源,当进程退出(例如文件句柄)时,这些资源应由操作系统自动处理。理论上我可以看到一个例子,如果说,你需要发送服务器一个特定的消息,由于崩溃退出。但是大多数时间的操作系统处理应该是足够的。

I've read that it can be used to make sure resources are freed -- but for the majority of resources this should be handled automatically by the OS when the process exits (e.g. file handles). Theoretically I can see a case for if say, you needed to send a server a specific message when exiting due to a crash. But the majority of the time the OS handling should be sufficient.

正在使用终止处理程序的Right Thing(TM)?

When is using a terminate handler the Right Thing(TM)?

更新:

推荐答案

这只是乐观:

关于操作系统自动处理的唯一资源是文件句柄和内存(这可能因操作系统而异)。
实际上所有其他资源(如果有人拥有由操作系统I
自动处理的资源列表)将需要由操作系统手动发布。

About the only resources that the OS handles automatically are "File Handles" and "Memory" (And this may vary across OS's).Practically all other resources (and if somebody has a list of resources that are automatically handled by OS's Iwould love that) need to be manually released by the OS.

最好的办法是避免使用terminate()退出,并尝试通过强制堆栈正确放松来控制关闭。
这将确保所有的析构函数被正确调用,资源被释放(通过析构函数)。

Your best bet is to avoid exit using terminate() and try a controlled shut down by forcing the stack to unwind correctly.This will make sure that all destructors are called correctly and your resources are released (via destructors).

关于我唯一要做的是记录问题。所以当它确实发生时,我可以回去修复代码,使其不再发生。我喜欢我的代码来很好地解决资源释放的堆栈,但这是一些意见,有些人喜欢在事情发生时突然停止。

About the only thing I would do is log the problem. So that when it does happened I could go back and fix the code so that it does not happen again. I like my code to unwind the stack nicely for resource deallocation, but this is an opinion some people like abrupt halts when things go badly.

一般来说,当异常处理机制找不到抛出异常的处理程序时,它被调用。一些具体的例子是:

In general it is called when the exception handling mechanism cannot find a handler for a thrown exception. Some specific examples are:


  • 异常转义main()


    • 注意:这是实现定义堆栈是否在这里展开。
      因此,我总是抓住主,然后重新抛出(如果我没有显式处理)。
      这样我保证堆栈(跨所有平台)的解放,并且仍然可以获得操作系统异常处理机制的好处。


    • 一个异常会在另一个异常传播时转义解析器。

    • 抛出的表达式会产生异常


    • 如果异常转义全局对象的构造函数/析构函数。

    • 如果异常转义了函数静态变量。
      (即注意非本地静态对象的构造函数/析构函数)

    • 异常转义使用atexit()注册的函数。


    • 通过意外。

    这篇关于什么时候是C ++终止处理程序Right Thing(TM)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:30