如http://en.cppreference.com/w/cpp/error/terminate中所述,有很多理由要求终止.我可以想象几乎在同一时间的情况,其中一些原因发生在两个线程中.
Q1终止功能设置std::set_terminate
可以同时被调用两次或更多次,同时我的意思是第一次呼叫在第一次结束之前开始.
Thread1 Thread2
| |
_ |
t |
e |
r |
m |
i _
n t
a e
t r
e m
- ?
Run Code Online (Sandbox Code Playgroud)
Q2如果Q1 == YES,那么如果第一次终止结束会发生什么.我想如果它以std :: abort结束,那么程序结束,但是如果用户提供的终止不会中止程序会发生什么?
Q3是否在std::set_terminate
导致此终止调用的线程的上下文中调用了terminate函数?
在哪个线程中称为终止处理程序:
当noexcept
函数内部抛出异常时?
当用户调用std::terminate
()?
在启动或破坏thread
?
它是否在标准中定义,我是否可以访问thread_local
对象?
我从cplusplus.com获取以下代码:
// set_terminate example
#include <iostream>
#include <exception>
#include <cstdlib>
using namespace std;
void myterminate () {
cout << "terminate handler called\n";
abort(); // forces abnormal termination
}
int main (void) {
set_terminate (myterminate);
throw 0; // unhandled exception: calls terminate handler
return 0;
}
Run Code Online (Sandbox Code Playgroud)
由于代码中存在未处理的异常,因此需要调用myterminate()函数,该函数设置为终止处理程序并且应该覆盖默认的终止处理程序.
程序崩溃但没有调用myterminate().我使用的是Visual C++ 2008 Express Edition.
代码有什么问题?
如果有以下程序的定义行为是什么?
#include <iostream>
#include <exception>
#include <cstdlib>
void i_throw()
{
std::cout << "i_throw()" << std::endl;
// std::terminate() is noexcept so if the terminate handler throws...
// then the terminate handler is called...
// std::terminate is [[noreturn]] so don't return
try
{
throw 7;
}
catch(...)
{
std::cout << "caught exception, re-throw()-ing" << std::endl;
throw;
}
std::cout << "got here!" << std::endl;
std::abort();
}
int main()
{
std::set_terminate(i_throw);
throw;
std::terminate();
}
Run Code Online (Sandbox Code Playgroud)
使用gcc和clang我得到以下输出:
i_throw()
caught exception, re-throw()-ing
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)
在前几条评论后编辑的示例.
(我不知道为什么我有两个 …
我有下面的例子。(我的实际项目是一个多线程项目,我为所有项目设置了终止处理程序。)我这里有几个问题。
我的终止处理程序没有做任何花哨的事情。它只是说发生了错误并退出。我读到添加处理程序是一个很好的做法。为什么会这样?在这种情况下我真的需要吗?
如果我没有处理程序,我会得到抛出的异常类型。terminate called after throwing an instance of 'char const*'
但是当我使用处理程序时,我无法获取它。即使我使用 current_exception,我也无法获取异常的类型。(这里显然是 char* 但在我的情况下它可能是任何东西,所以我无法正确捕获。即使我使用 catch{...},消息和类型也会丢失)。无论如何都可以得到消息。如果不是消息,至少我可以获得抛出的异常的类型?
// set_terminate example
#include <iostream>
#include <exception>
#include <cstdlib>
using namespace std;
void myterminate () {
cerr << "terminate handler called\n";
abort(); // forces abnormal termination
}
int main (void) {
//set_terminate (myterminate);
throw "TEST"; // unhandled exception: calls terminate handler
return 0;
Run Code Online (Sandbox Code Playgroud)