Aart Stuurman
Aart Stuurman

Reputation: 3598

Valid to use future after corresponding promise leaves scope

If you extract a future from a promise, is it valid to call future::get_value after the promise leaves scope?

std::future<void> future;
{
    std::promise<void> promise;
    future = promise.get_future();
    promise.set_value();
}
future.wait();

I am unable to find an answer using promise's and future's documentation.

Upvotes: 3

Views: 1321

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

Promises and future have a shared state.

A future whose promise was not fullfilled and was destroyed is a broken promise. The shared state is given an exception and made ready.

But a future whose promise was fullfilled and then the promise was destroyed is perfectly ok. The shared state persists.

Look at ~promise and the discussion about shared state on the main doc page.

Upvotes: 5

Related Questions