【问题标题】:What happens if the handler in set_terminate does not abort?如果 set_terminate 中的处理程序没有中止会发生什么?
【发布时间】:2018-03-27 01:13:36
【问题描述】:

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

如果我理解得很好,就会调用 std::terminate() (在头异常中),例如,当没有捕获到异常时。我read(也是here)默认将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
}

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

【问题讨论】:

  • 我相信它的未定义行为

标签: c++ exception terminate


【解决方案1】:

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

[terminate.handler]

必需的行为:terminate_handler 应终止程序的执行而不返回调用者。

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

【讨论】:

  • 谢谢,但我仍然想知道标准定义中“终止”的确切含义。该标准并不等同于调用 abort()。也可以调用 exit(),虽然这不是很一致,因为它不再是异常终止。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
相关资源
最近更新 更多