-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