liveBook · Manning

Coroutine handle

As explained in Learn C++ by Example

std::coroutine_handle is the C++ standard-library type that provides access to coroutine execution and destruction operations.

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

How Learn C++ by Example covers it

How deep it goes
Explains from_promise, done, operator()(), and destroy, while deferring broader co_await implementation.
Examples
Demonstrates typed handle construction, completion checks, resumption, and a custom RAII deleter.
What it assumes
Assumes familiarity with C++ coroutines, promise_type, Task, suspension, and RAII resource ownership.
What you can do after
Operate coroutine execution through a Task wrapper that resumes, checks, and destroys its coroutine frame.
How it connects
Connects coroutine handles to promise_type, Task, co_yield, final_suspend, RAII, and unique_ptr.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.