在设置值之前必须调用 promise.get_future() 吗?

Fel*_*bek 5 c++ future promise

http://www.cplusplus.com/reference/future/promise/get_future/

调用此函数后,promise 有望在某个时刻准备好其共享状态 [...]

我不确定这是否意味着此操作顺序是强制性的:

  1. get_future()
  2. 设定值()

只有在设置了一个值之后,是否还有可能从承诺中获得未来?

Dmi*_*don 3

据我所知,没有这样的限制。std::promise::set_value导致错误的唯一两种情况是:

  1. Promise 对象没有共享状态(当 Promise 对象被移动时可能会发生这种情况):

    promise<int> p;
    auto p2 = std::move(p);
    p.set_value(42); // error
    
    Run Code Online (Sandbox Code Playgroud)
  2. 共享状态已经存储了一个值或异常:

    promise<int> p;
    p.set_value(0);
    p.set_value(42); // error
    
    Run Code Online (Sandbox Code Playgroud)

    或者

    promise<int> p;
    try 
    {
        throw std::runtime_error("Some error");
    } 
    catch(...) 
    {
        p.set_exception(std::current_exception());
        p.set_value(42); // error
    }
    
    Run Code Online (Sandbox Code Playgroud)

get_future但之前调用没有限制。