小编Tin*_* LI的帖子

工作线程中的C++未捕获异常

未捕获的异常对主线程和另一个std :: thread的行为有所不同.

这是测试程序

#include <thread>

class XXX{
public:
  XXX(){std::fprintf(stderr, "XXX ctor\n");}
  ~XXX(){std::fprintf(stderr, "XXX dtor\n");}
};

void mytest(int i)
{
    XXX xtemp;
    throw std::runtime_error("Hello, world!");
}
int main(int argc, char *argv[])
{
    if(argc == 1) {
        mytest(0);
    }else{
        std::thread th([&]{mytest(0);});
        th.join();
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码(C++ 11),由GCC 5.4编译运行,没有args

XXX ctor
terminate called after throwing an instance of 'std::runtime_error'
   what():  Hello, world!
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)

运行1 arg:

XXX ctor
XXX dtor
terminate called after throwing an instance of 'std::runtime_error'
  what():  Hello, world!
Aborted …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading stack-unwinding uncaught-exception

5
推荐指数
1
解决办法
553
查看次数