-1
我有一个非常简单的程序为:C++ 11:Mac上的Clang不会捕获std :: thread函数抛出的异常?
#include <iostream>
#include <string>
#include <thread>
using namespace std;
struct N{
string s;
N(){}
~N(){cout<<"N dtor"<<endl;}
};
void f(){
N n;
throw 0;
}
int main(){
try{
thread a(f), b(f);
a.join();
b.join();
}catch(exception& e){
cout<<e.what()<<endl;
}
return 0;
}
在我的Mac +铛环境,运行结果是:
libc++abi.dylib: terminating with uncaught exception of type int
Abort trap: 6
它不打印“N析构函数”,因为我预期。所以我的问题,如果std :: thread函数抛出一个异常,如何捕捉/处理它?不能保证线程函数内的代码不会抛出任何异常。
我试图在Linux和异常可以被捕获并打印:
Enable multithreading to use std::thread: Operation not permitted
非常感谢。
如果您想将异常传输到调用线程,请使用'std :: async'。 – ecatmur