gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:49:24 30 4
gpt4 key购买 nike

通过 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函数在函数外捕获这样的异常是不是对的?

最佳答案

来自 cppreference :

[...] if the function f returns a value or throws an exception, it is stored in the shared state accessible through the std::future that async returns to the caller.

并在关于 std::future::get() 的引用中:

If an exception was stored in the shared state referenced by the future (e.g. via a call to std::promise::set_exception()) then that exception will be thrown.

所以是的,如果您的函数抛出异常,该异常基本上会被推迟到将来并在 get() 上重新抛出。

关于c++ - 从通过 std::async 启动的函数抛出的异常会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41855401/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com