I don't believe that cppreference is entirely accurate in this case.
The standard says that the dtor for std::future
releases any shared state (§[futures.unique_future]/9):
~future();
Effects:
- Releases any shared state (31.6.5);
- destroys
*this
.
The description of releasing the shared state says (§[futures.state]/5):
When an asynchronous return object or an asynchronous provider is said to release its shared state, it means:
- if the return object or provider holds the last reference to its shared state, the shared state is destroyed; and
- the return object or provider gives up its reference to its shared state; and
- these actions will not block for the shared state to become ready, except that it may block if all of the following are true: the shared state was created by a call to
std::async
, the shared state is not yet ready, and this was the last reference to the shared state.
[emphasis added]
Summary
In essence, the code has undefined behavior. While an implementation is allowed generate code to block for the shared state to become ready, it is not required to do so, and is not even required to document whether it will do so or not. As such, what you have is pretty much the typical situation for undefined behavior: you may get what you expect, but it isn't required.
Reference
I quoted from N4713, which (if memory serves) is pretty much the C++17 standard. It looks like the wording remains the same up through at least N4950 (which is pretty much C++23.).
std::async
is special - it always blocks in a destructor, so the output is guaranteed to bez
- there are no races here.async
can't happen until afterx
has been modified by the first call.x
in this code.