如果 set_terminate 中的处理程序不中止会发生什么?

and*_*ipb 5 c++ exception terminate

如果 set_terminate 指示的处理程序本身不调用 abort(),程序的行为是什么?

如果我理解得很好,则调用 std::terminate() (在标头异常中),例如,当未捕获异常时。我读到(也在此处) std::terminate() 默认定义为对 std::abort() 的调用,但可以使用 set_terminate(handler) 进行修改。 如果新处理程序不调用 abort() 怎么办?是默认添加的吗?

我在下面说明了我不理解的行为。在一条短消息之后,terminate() 的新处理程序可以中止、调用终止或退出。如果这些选项均未设置,则程序会异常终止。但如果插入 abort() 也会发生同样的事情。如果我们使用exit(),程序会以成功结束,并在exit(..)中写入错误代码。如果我们调用terminate(),我们就会陷入无限循环(运行失败,代码127)。

这是在 Windows 8.1 计算机上使用 MinGW 6.3.0 和 NetBeans。

void myOwnOnExit() {
  cerr << "called myOwnOnExit\n";
}
void myOwnTerminate() {
  cerr << "called myOwnTerminate\n";
  // Uncomment one of the following:
  // // if none is uncommented, abnormal termination, error 3
  // abort();      // with or without it, abnormal termination, error 3
  // terminate();  // get an infinite loop, error code 127 in 3 seconds
  // exit(EXIT_SUCCESS); // displays "called myOwnOnExit", success 
}
int main() {
  atexit(myOwnOnExit);
  set_terminate(myOwnTerminate);
  throw 1;
  cerr << "we should not see this"; // and we don't
}
Run Code Online (Sandbox Code Playgroud)

非常感谢您的任何提示或建议。

lll*_*lll 5

您应该在 a 中终止程序terminate_handler,这是标准要求的:

\n\n

[终止处理程序]

\n\n
\n

所需行为:terminate_\xc2\xadhandler 应终止程序的执行而不返回到调用者。

\n
\n\n

因此,如果您的处理程序无法满足要求,则这是未定义的行为。

\n

  • 谢谢,但我仍然想知道标准定义中的“终止”到底意味着什么。标准并不将其等同于调用 abort()。也可以调用 exit(),尽管这不太一致,因为它不再是异常终止。 (2认同)