What gives a std::future some shared state
Asked Answered
B

1

3

A std::future has a std::future::valid method, which indicates whether the future object refers to some shared state. None of the constructors construct a future object that refers to shared state (except the move constructor, which can move the shared state from one future object to another). All the methods of the class (get, wait, wait_for and wait_until require the future object to have shared state as a precondition (they have undefined behaviour if valid() == false). How then can a std::future acquire some shared state and become useful?

Bosket answered 25/4, 2018 at 11:10 Comment(2)
I am answering my own question, as is encouraged.Bosket
More power to you, especially since you posted the two in tandem (some users don't, and it's confusing).Lyris
B
5

You do not normally use a std::future in isolation; you use it with a std::promise. The std::promise constructors set up some shared state. You can then use the std::promise::get_future() method to get a std::future that refers to that shared state.

Bosket answered 25/4, 2018 at 11:10 Comment(2)
Perhaps an example would be useful?Swanky
std::async and std::packaged_task also create futuresWistful

© 2022 - 2024 — McMap. All rights reserved.