从通过std :: async启动的函数抛出的异常会发生什么

Fro*_*art 2 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 << "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;
  }
}
Run Code Online (Sandbox Code Playgroud)

MSVC给我以下输出:

1
foo()
Error
Run Code Online (Sandbox Code Playgroud)

是否通过调用get函数将这些异常捕获到函数外部?

Bar*_*rry 8

cppreference:

[...]如果该函数f返回一个值或抛出异常,它是存储在通过所述访问的共享状态std::futureasync返回给调用者.

并在参考中std::future::get():

如果异常存储在未来引用的共享状态中(例如通过调用std::promise::set_exception()),那么将抛出该异常.

所以,是的,如果你的函数抛出异常,那么该异常基本上会延迟到将来并重新开始get().