Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does promise.get_future() have to be called before setting a value?

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

After this function has been called, the promise is expected to make its shared state ready at some point [...]

I'm unsure if this implies that this order of operations is mandatory:

  1. get_future()
  2. set_value()

Would it also be possible to get the future from the promise only after a value has been set?

like image 700
Felix Dombek Avatar asked Oct 28 '22 14:10

Felix Dombek


1 Answers

As far as I see there is no such limitation. The only two cases when std::promise::set_value leads to error are:

  1. Promise object has no shared state (this can occur when promise object is being moved):

    promise<int> p;
    auto p2 = std::move(p);
    p.set_value(42); // error
    
  2. The shared state already stores a value or exception:

    promise<int> p;
    p.set_value(0);
    p.set_value(42); // error
    

    or

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

But there is no limitation for get_future to be called before.

like image 118
Dmitry Gordon Avatar answered Nov 15 '22 06:11

Dmitry Gordon