Advertisement
Advanced C++, Coroutines

What are the coroutine machinery components (promise_type, awaitable, coroutine_handle)?

Short answer

A coroutine's return type must provide a promise_type controlling its behavior (initial/final suspend, how co_yield/co_return/exceptions are handled, and how the return object is built). An awaitable (with await_ready/await_suspend/await_resume) defines what co_await does.

Save C++ mock interview
Advertisement
AModel answer
A coroutine's return type must provide a promise_type controlling its behavior (initial/final suspend, how co_yield/co_return/exceptions are handled, and how the return object is built). An awaitable (with await_ready/await_suspend/await_resume) defines what co_await does. coroutine_handle is a low-level handle to resume/destroy the coroutine. The standard library provides little out of the box before C++23's std::generator, so libraries or hand-written types supply these.
struct promise_type {
    auto get_return_object();
    std::suspend_always initial_suspend();
    std::suspend_always final_suspend() noexcept;
    void return_void(); void unhandled_exception();
};
Real-world example
A library author writes a Task type with a promise_type to integrate coroutines with its event loop.
Likely follow-ups
  • What does promise_type control? | What is an awaitable?
Related topics