stdfuture 错误和 stdfuture errc

如果不满足 std::promise 和 std::future 的约束,则抛出 std::future_error 类型的异常。

异常中的错误代码成员是 std::future_errc 类型,值如下,以及一些测试用例:

enum class future_errc {
    broken_promise             = /* the task is no longer shared */,
    future_already_retrieved   = /* the answer was already retrieved */,
    promise_already_satisfied  = /* the answer was stored already */,
    no_state                   = /* access to a promise in non-shared state */
};

不活跃的承诺:

int test()
{
    std::promise<int> pr;
    return 0; // returns ok
}

积极的承诺,未使用:

  int test()
    {
        std::promise<int> pr;
        auto fut = pr.get_future(); //blocks indefinitely!
        return 0; 
    }

双重检索:

int test()
{
    std::promise<int> pr;
    auto fut1 = pr.get_future();

    try{
        auto fut2 = pr.get_future();    //   second attempt to get future
        return 0;
    }
    catch(const std::future_error& e)
    {
        cout << e.what() << endl;       //   Error: "The future has already been retrieved from the promise or packaged_task."
        return -1;
    }
    return fut2.get();
}

设置 std::promise 值两次:

int test()
{
    std::promise<int> pr;
    auto fut = pr.get_future();
    try{
        std::promise<int> pr2(std::move(pr));
        pr2.set_value(10);
        pr2.set_value(10);  // second attempt to set promise throws exception
    }
    catch(const std::future_error& e)
    {
        cout << e.what() << endl;       //   Error: "The state of the promise has already been set."
        return -1;
    }
    return fut.get();
}