如果在加入子线程之前抛出异常,有什么方法可以防止程序终止?

Is there any way to prevent the program from termination if an exception was thrown before a child thread had been joined?

//...
try
{
    std::thread someThread(someFunc, someArg); // assume it doesn't throw
    foo(); // might throw
    bar(); // might throw
    someThread.join();
}
//...

在上面的例子中,如果 foo()bar() 抛出,someThread 的析构函数将调用 terminate() 函数,因为 someThread 没有由于堆栈展开而被加入父线程,这将导致整个程序终止。有没有办法在不终止程序的情况下防止这种行为并处理异常?

一种选择是在 try/catch 块之前简单地声明 someThread 并在 try 子句中使用移动赋值。然后可以在 catch 子句之后立即调用 join...

std::thread someThread;
try
{
    someThread = std::thread(someFunc, someArg);
    foo(); // might throw
    bar(); // might throw
}
catch (...) {

    /*
     * Do some error handling...
     */
}
if (someThread.joinable())
    someThread.join();

或者,如果您的编译器支持 c++20,您可能需要查看 std::jthread