A coroutine handle is the access point for controlling a coroutine frame. It can resume execution, report whether the coroutine is finished, and destroy the frame when its owner is done with it. section 8.3.3 section 8.3.6
A Task wrapper commonly obtains and uses its handle in three ways:
- Construct a typed handle from a promise with std::coroutine_handle<promise_type>::from_promise(*promise). section 8.3.4
- Call done() to test the completion flag set after final_suspend. section 8.3.5 section 8.3.6
- Invoke the handle with operator()() to resume a coroutine paused by co_yield. section 8.3.6
- Call destroy() when the coroutine frame must be released, often through a custom RAII deleter. section 8.3.4
Resuming a yielded game coroutine
A Task exposes next() by rebuilding a handle from its promise and calling handle(). The caller reads the yielded choice and prediction, then calls next() for the following pair; done() indicates that final_suspend has been reached. section 8.3.6 section 8.3.5
Listing 8.18 Custom "deleter"
template<typename Promise> #1
struct coro_deleter #1
{ #1
void operator()(Promise* promise) const noexcept #1
{
auto handle =
std::coroutine_handle<Promise>::from_promise(
*promise
); #2
if (handle) #3
handle.destroy(); #3
}
};
A custom deleter shows how to recover a typed coroutine handle from a promise and safely call destroy(). section 8.3.4
