【问题标题】:std future exception - already retrieved, std bug?标准未来异常 - 已检索,标准错误?
【发布时间】:2015-09-18 09:21:07
【问题描述】:

我正在尝试捕获在 http://www.cplusplus.com/reference/future/future_errc/ 中看到的 Already-Retrieved 异常

try {
    prom.get_future();
    prom.get_future();   // throws std::future_error with future_already_retrieved
}
catch (std::future_error& e) {
    if (e.code() == std::make_error_condition(std::future_errc::future_already_retrieved))
        std::cerr << "[future already retrieved]\n";
    else
        std::cerr << "[unknown exception]\n";
}

但我总是收到无状态例外。 通过查看 std 未来的实现:

_Ty& _Get_value() const
{   // return the stored result or throw stored exception
    if (!valid())   // will check if already retrieved, and return false
        _Throw_future_error(make_error_code(future_errc::no_state));
        return (_Assoc_state->_Get_value(_Get_only_once)); // only this
            // method can throw the already retrieved exception but its not
            // being hit because of previous valid() check
}

这是 Visual Studio 2013 中的错误还是功能?

【问题讨论】:

  • 你应该看std::promisestd::packaged_task的实现(具体来说,std::promise::get_futurestd::packaged_task::get_future的实现),而不是std::future之一。
  • 是的,这在我看来像是一个 Visual Studio 错误。

标签: c++ c++11 exception-handling promise c++-standard-library


【解决方案1】:

来自cppreference,我觉得更可靠:

如果 *this 没有共享状态或 get_future 已被调用,则会引发异常。

什么例外?

如果*this 没有共享状态,或者如果 get_future 已在与 *this 具有相同共享状态的承诺上被调用,则抛出:future_error。

  • (14.1) future_already_retrived 如果 get_future 已经被调用 promise 与 *this 具有相同的共享状态。
  • (14.2) no_state if *this 没有共享状态。

所以这是 MSVC2013 中的一个错误。

【讨论】:

  • 但是 OP 没有调用 future::get()promise::get_future() 是完全不同的函数。
  • @JonathanWakely 嗯。不知道我在想什么,但这是错误的。答案已更正。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-04
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
相关资源
最近更新 更多