Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 通过std::async启动的函数引发的异常会发生什么情况_C++_Multithreading_C++11 - Fatal编程技术网

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