我的理解是,当异步操作抛出异常时,它将被传播回调用std::future::get()
的线程。但是,当这样的线程调用std::future::wait()
时,异常不会立即传播 - 随后调用std::future::get()
将引发异常。异常传播和std :: future
但是,在这种情况下,如果在呼叫std::future::wait()
后未来对象超出范围,但在致电std::future::get()
之前,会发生这种异常?
对于那些有兴趣的人,这里是一个简单的例子。在这种情况下,异常悄悄由线程/未来包处理:
#include "stdafx.h"
#include <thread>
#include <future>
#include <iostream>
int32_t DoWork(int32_t i)
{
std::cout << "i == " << i << std::endl;
throw std::runtime_error("DoWork test exception");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
auto f = std::async(DoWork, 5);
try
{
//f.get(); // 1 - Exception does propagate.
f.wait(); // 2 - Exception does NOT propagate.
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
return -1;
}
return 0;
}
我_think_什么也没有发生异常,它只是被忽略。 (但是我对此一点都不熟悉,可以肯定。) – Mat
我认为注意到异常是通过'std :: exception_ptr's在线程间传播的。所以对系统来说,异常看起来会被捕获和处理,直到传播机制决定重新抛出它为止。 –