【发布时间】:2017-05-15 20:13:08
【问题描述】:
假设你有以下代码
void func(std::promise<int> prom) {
try {
auto promise = std::promise<int>{std::move(prom)};
// .. do stuff
throw std::runtime_error{"something went wrong"};
} catch (...) {
// cleanup and dont bother with the promise
}
}
auto promise = std::promise<int>{};
auto future = promise.get_future();
std::thread{[promise = std::move(promise)] {
func(std::move(promise));
}}.detach();
try {
cout << future.get() << endl;
} catch (std::exception& exc) {
cerr << exc.what() << endl;
}
当 Promise 被销毁并在未来结束时重新传播相同的异常时,没有捕获正在传播的异常的原因是什么?为什么在这种情况下总是抛出一个破承诺异常?
我只是觉得在未来重新传播相同的异常是很自然的。
为了澄清我的意思,除了set_exception() 方法之外,我认为调用set_exception(std::current_exception()) 的析构函数可能是个好主意
在捕获异常并存储对它的引用后,析构函数将重新抛出异常
【问题讨论】:
-
你应该使用
set_exception在promise对象中设置异常。 -
@WhiZTiM 我知道这一点,我只是想知道为什么捕获传播异常并调用
set_exception是个坏主意
标签: c++ c++11 exception c++14 future