通过std::async
启动的函数引发的异常会发生什么情况?
#include <future>
#include <iostream>
#include <stdexcept>
void foo()
{
std::cout << "foo()" << std::endl;
throw std::runtime_error("Error");
}
int main()
{
try
{
std::cout << "1" << std::endl;
auto f = std::async(std::launch::async, foo);
f.get();
std::cout << "2" << std::endl;
}
catch (const std::exception& ex)
{
std::cerr << ex.what() << std::endl;
}
}
MSVC 为我提供了以下输出:
1
foo()
Error
通过调用 get
函数在函数外部捕获此类异常是否正确?
来自 cpp首选项:
[...]如果函数
f
返回一个值或抛出一个异常,它将存储在共享状态中,可通过async
返回给调用方的std::future
访问。
在关于std::future::get()
的参考资料中:
如果异常存储在将来引用的共享状态中(例如,通过调用
std::promise::set_exception()
),则将抛出该异常。
所以是的,如果你的函数抛出一个异常,该异常基本上会推迟到将来并在get()
重新抛出。