sam
sam

Reputation: 866

std::future is set to 'empty' state c++

The sr.tFuture is initialized with 'empty' state instead of 'pending' and I found out when I remove tFuture() from the constructor initialization list, the state of sr.tFuture becomes pending which is correct. But I don't quite understand the reason. Is it because the value of tFuture on the declaration part gets overwritten when tFuture() gets invoked and cause tFuture to not get associated with any promise?

struct SharedResource
{
    SharedResource(const SharedResource&) = delete;
    SharedResource& operator=(const SharedResource&) = delete;
    SharedResource() :
        tPromise(), tFuture()
        {}

    std::promise<void> tPromise;
    std::future<void> tFuture = tPromise.get_future();
};

int main()
{
    SharedResource sr;
}

Upvotes: 1

Views: 654

Answers (1)

Dhwani Katagade
Dhwani Katagade

Reputation: 1290

This answer just tries to summarize the overall understanding and resolution to the problem posted in the question, sourced majorly from the comments by françois-andrieux.


To begin with, a few clarifications.

  • What the OP refers to as an 'empty' future is better called a default constructed or an invalid future, one that does not refer to a valid shared state. Futures are not created this way but instead retrieved from an asynchronous provider like std::promise, std::packaged_task or std::async.
  • What the OP refers to as a 'pending' future is one that has a valid shared state that is not yet ready. That is, a future that has been retrieved from a promise, but the promise has not yet set a value or exception on the shared state. This is the right way of creating a valid future.

The confusing behavior that is observed in the question is that

  • in one case, where the future is initialized from the constructor initializer list, the future gets default constructed as an invalid future as tFuture().
  • in the other case where tFuture() is removed from the constructor initializer list, it gets initialized from the default initializer as tPromise.get_future();.

The first case sets up an invalid future, the one that OP refers to as 'empty', where as the second case sets up a proper valid future.

Upvotes: 0

Related Questions