Modern C++ › C++20
Coroutines
co_await, co_yield and co_return.
Explanation
A coroutine is a function that can suspend and later resume, keeping its local state in a heap-allocated coroutine frame. A function is a coroutine if its body uses any of:
| Keyword | Meaning |
|---|---|
co_yield value |
produce a value and suspend (generators) |
co_await expr |
suspend until expr is ready (async I/O, tasks) |
co_return value |
finish and deliver a result |
C++20 provides the language mechanism only. Your coroutine’s return type must define a nested promise_type that controls its behavior (how it starts, what happens at the end, what co_yield stores, how exceptions are handled), and you work with the coroutine through a std::coroutine_handle (resume(), done(), destroy()). Most users get these from libraries (cppcoro, libunifex, Boost.Asio, folly::coro). C++23 adds std::generator.
The two predefined awaiters are std::suspend_always and std::suspend_never.
Example
A minimal generator written from scratch to show the moving parts:
#include <coroutine>
#include <exception>
#include <iostream>
#include <utility>
template <typename T>
class Generator {
public:
struct promise_type {
T current;
Generator get_return_object() {
return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept { return {}; } // start suspended
std::suspend_always final_suspend() noexcept { return {}; } // keep frame for done()
std::suspend_always yield_value(T value) { // co_yield lands here
current = std::move(value);
return {};
}
void return_void() {}
void unhandled_exception() { std::terminate(); }
};
explicit Generator(std::coroutine_handle<promise_type> h) : handle_(h) {}
Generator(Generator&& o) noexcept : handle_(std::exchange(o.handle_, {})) {}
~Generator() { if (handle_) handle_.destroy(); }
bool next() { handle_.resume(); return !handle_.done(); } // run to the next co_yield
const T& value() const { return handle_.promise().current; }
private:
std::coroutine_handle<promise_type> handle_;
};
Generator<long long> fibonacci(int count) {
long long a = 0, b = 1;
for (int i = 0; i < count; ++i) {
co_yield a; // suspend here; resume continues the loop
long long next = a + b;
a = b;
b = next;
}
}
Generator<int> countdown(int from) {
for (int i = from; i > 0; --i) co_yield i;
}
int main() {
auto fib = fibonacci(10);
while (fib.next()) std::cout << fib.value() << " "; // 0 1 1 2 3 5 8 13 21 34
std::cout << "\n";
auto cd = countdown(3);
while (cd.next()) std::cout << cd.value() << "... ";
std::cout << "liftoff\n";
return 0;
}
Common pitfalls
- Dangling references: a coroutine frame stores copies of parameters, but a reference parameter still refers to the caller’s object. If the coroutine outlives it, you read freed memory.
- Forgetting to
destroy()the handle leaks the frame; wrap it in an RAII type as above. - Calling
resume()on a finished coroutine is undefined behavior; checkdone(). - Lambdas that are coroutines and capture variables: the lambda object can die before the coroutine finishes.
- The compiler may heap-allocate the frame; avoid coroutines in the tightest loops unless the allocation is elided.
- Debugging is harder: the stack trace doesn’t show suspended callers.
Legacy vs modern
Before C++20, the same control flow needed hand-written state machines, callbacks / continuations (std::future::then is not standard), threads, platform fibers (Win32 CreateFiber, ucontext), or macro tricks (Duff’s device, protothreads). Coroutines let async code read sequentially (auto data = co_await socket.read();) without callback pyramids. See Threads, Mutexes and Atomics for the thread-based alternative.
Exercises
1. Which function type signals to the compiler that int f() is a coroutine?
No signature marks it. The presence of co_await, co_yield or co_return in the body makes it a coroutine, and its return type must provide a promise_type.