skip to content

In C++20, what turns an ordinary function into a coroutine, and how does the compiler find the promise_type that drives it?

level: middleimportance: should knowfreq 42%

answer

  1. the body decides, not the signature
  2. three keywords
  3. coroutine_traits of return and parameters
  4. R::promise_type by default
  5. no auto, no varargs, no return

basics

~10 s

A function is a coroutine if its body contains co_await, co_yield or co_return; its declaration looks unchanged. The compiler uses std::coroutine_traits<R, Args...>::promise_type, which by default is the return type's nested promise_type.

solid answer

~50 s

Nothing in the declaration marks a C++20 coroutine: the **body** does, by containing `co_await`, `co_yield` or `co_return`. The compiler then needs a **promise type**, which it takes from `std::coroutine_traits<R, P1, ..., Pn>::promise_type`, where `R` is the return type and the `P`s are the parameter types (with the object parameter first for a member function). The primary template simply forwards to `R::promise_type`, so most libraries nest the promise in the return type; specialising `std::coroutine_traits` lets you adapt a return type you do not own. The compiler rewrites the body around a promise object: `get_return_object()`, `co_await initial_suspend()`, your code inside a try block whose handler calls `unhandled_exception()`, then `co_await final_suspend()`. A coroutine cannot use a deduced (`auto`) return type, a C-style ellipsis or a plain `return`, a non-template `constexpr` or `consteval` function cannot be one, and neither can `main`, constructors or destructors.

code

cpp · 7 lines
cpp
#include <coroutine>

// Any co_await, co_yield or co_return in the body makes this a coroutine,
// and a coroutine cannot deduce its return type.
auto answer() {
    co_return 42;
}

go deeper

for a junior

Recall the three keywords that make a function a coroutine and that its return type must supply a promise_type, usually as a nested type.

for a middle

Explain coroutine_traits, the replacement body around initial_suspend and final_suspend, and the list of functions that cannot be coroutines.

for a senior

Read an unfamiliar promise type and predict lazy or eager start, how results and exceptions reach the caller, and what flowing off the end does.

for a principal

Decide which promise types the codebase may define, since every coroutine's behavior is set by a promise someone must own and review.

## The body decides In C++20 a function is a **coroutine** if its function body contains any of: - a `co_await` expression, which may suspend until an awaitable is ready; - a `co_yield` expression, which hands a value out and suspends; - a `co_return` statement, which finishes the coroutine. The declaration does not change. `Task<int> load(int id);` may be a coroutine or an ordinary function returning a `Task<int>`; only the definition tells. Callers cannot see the difference, which is the point: a coroutine is an implementation detail behind an ordinary function type. ## Finding the promise type The compiler needs a **promise type** to decide what the coroutine does at each step. The rule: 1. Form `std::coroutine_traits<R, P1, ..., Pn>`, where `R` is the declared return type and `P1 ... Pn` are the parameter types; for a non-static member function the type of the object parameter comes first. 2. Use its nested `promise_type`. The primary template from `<coroutine>` defines `promise_type` as `R::promise_type` when that names a type. 3. The promise type must be a class type. So the everyday pattern is a return type with a nested `struct promise_type`. Specialising `std::coroutine_traits` is the escape hatch for a return type you cannot edit. ## What the compiler builds around your body The standard describes a **replacement body**. In simplified form: ```cpp { promise_type promise; // possibly constructed from the parameters // the caller receives promise.get_return_object() try { co_await promise.initial_suspend(); /* your function body */ } catch (...) { promise.unhandled_exception(); } final_suspend: co_await promise.final_suspend(); } ``` | Promise member | When it runs | Typical use | |---|---|---| | `get_return_object()` | before `initial_suspend` | builds the object the caller gets, often holding a `std::coroutine_handle` | | `initial_suspend()` | at the start | `std::suspend_always` = lazy, `std::suspend_never` = eager | | `yield_value(e)` | at `co_yield e` | stores the value, returns an awaitable that suspends | | `return_void()` / `return_value(v)` | at `co_return` | records the result; a promise may declare one or the other, not both | | `unhandled_exception()` | when the body throws | store `std::current_exception()` or terminate | | `final_suspend()` | at the end | must not be potentially-throwing; deciding whether to stop before the frame is freed | If the promise has no `return_void`, flowing off the end of the coroutine is **undefined behavior**; with `return_void` it is an implicit `co_return;`. ## What cannot be a coroutine The standard rules out several cases, each of which the compiler diagnoses: - a function with a **placeholder return type** (`auto`, `decltype(auto)`) — clang says `'co_return' cannot be used in a function with a deduced return type`; - a parameter list ending in a C-style **ellipsis** (a template parameter pack is fine); - a body containing a plain **`return`** statement; - non-template `constexpr` and `consteval` functions, because a coroutine is never constexpr-suitable (an instantiated constexpr function template that is a coroutine simply is not usable in constant expressions); - `main`, **constructors** and **destructors**. `co_await` is also not allowed inside a `catch` handler; clang reports `'co_await' cannot be used in the handler of a try block`. ## When the promise is incomplete The compiler checks the promise against what the body uses, so a missing member is a compile error at the coroutine, not a runtime surprise: - `co_return;` with no `return_void` — clang reports `no member named 'return_void' in 'Lazy::promise_type'`; - `co_yield` with no `yield_value`, or a missing `initial_suspend`, `final_suspend` or `get_return_object`, fails the same way; - declaring both `return_void` and `return_value` makes the program ill-formed. The one gap the compiler does not catch is the runtime one above: flowing off the end of a coroutine whose promise has only `return_value`. ## What the standard library gives you C++20 ships only the low-level pieces in `<coroutine>`: `std::coroutine_traits`, `std::coroutine_handle<Promise>`, `std::suspend_always`, `std::suspend_never` and `std::noop_coroutine()`. It ships **no** ready-made coroutine return type; C++23 adds `std::generator`. Every coroutine therefore uses a promise written by you or by a library — which is why interviewers ask what that promise has to provide.

  • How does a member-function coroutine's promise see the object it was called on?
    For a non-static member function the object parameter's type is the first argument to `std::coroutine_traits`, and if the promise type has a constructor taking the object and the parameters, the compiler calls it with `*this` and the parameter copies. That is how a promise can record which object or allocator a coroutine belongs to; otherwise the promise is default-constructed.
  • What does the caller get back from a coroutine call?
    The result of `promise.get_return_object()`, called before `initial_suspend`. The call returns to the caller at the coroutine's first suspension point (or when it finishes), and the caller receives that object — typically a type wrapping a `std::coroutine_handle<promise_type>` so it can resume the coroutine, read results and destroy the frame.

  • A coroutine must be declared with a special keyword or attribute.
  • The compiler looks for std::promise<R> from the future header.
  • A coroutine can return auto like any other function.
  • Flowing off the end of any coroutine is the same as co_return.
  • Constructors can be coroutines if they co_await a resource.

Assumes C++23; coroutines and <coroutine> arrived in C++20, and C++23 adds std::generator as the first standard coroutine return type.