C++ 通过std::async启动的函数引发的异常会发生什么情况
通过C++ 通过std::async启动的函数引发的异常会发生什么情况,c++,multithreading,c++11,C++,Multithreading,C++11,通过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 <
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;
}
}
通过调用get
函数在函数外部捕获此类异常是否正确?来自:
[…]如果函数f
返回一个值或抛出一个异常,它将存储在共享状态,可通过std::future
访问该状态,该状态将async
返回给调用方
参考文献中关于:
如果异常存储在将来引用的共享状态中(例如,通过调用std::promise::set_exception()
),则将引发该异常
因此,是的,如果您的函数抛出异常,则该异常基本上被推迟到将来,并在
get()
RTFM上重新抛出。RTFM。实际上,这是一个非常好的功能,专门为您的方便而设计和实现。否则,该异常将失去任何捕获和处理的机会it@PeteBecker每天学习新的缩写词!
1
foo()
Error