C++20

C++20 Coroutine Pitfalls: Three Fixtures, Three Compilers, Same Answer

A coroutine can run its body at creation, or not at all until the first resume, depending on one function in the promise type. A resource held inside a coroutine frame is released the moment the generator is destroyed, not when the loop would have finished. A lazy task that is never resumed never runs its body.

Written November 7, 2026 · Tested with GCC 13.3.0 · 6 min read

By the end of this guide
  • Fixture 1: eager versus lazy start
  • Fixture 2: the frame is destroyed when the generator is destroyed
  • Fixture 3: a lazy task runs nothing until resumed

What this guide is

This guide is three programs and the output of each one. Every program uses a hand-rolled promise type, C++20 only, with no standard generator type and no extra compiler flag. All nine runs returned 0, and the output of each program was byte-identical on all three compilers. The guide states what the output proves and nothing more.

The framework behind these programs — the promise type, the handle that owns the frame, the iterator that resumes it — is built in the previous guide, C++20 Coroutines to C++23 std::generator. This guide does not rebuild it. It takes the framework as given and tests three behaviors that surprise people who use it.

The reference for the rules behind the fixtures is cppreference, Coroutines (C++20). It states that initial_suspend decides the start: a promise type returns suspend_always for lazily-started coroutines or suspend_never for eagerly-started coroutines, and the body starts only when the co_await on initial_suspend resumes. It also states that the coroutine state holds the promise object, the parameter copies, and the local variables whose lifetime spans a suspension point, and that destroying the state through the handle ends the coroutine. The three fixtures below are the observed behavior that follows from those rules.

Fixture 1: eager versus lazy start

Whether a generator body runs at creation is decided by one function, initial_suspend, in the promise type. A promise type that returns suspend_never starts eagerly: the body runs to the first co_yield during the call that creates the generator. A promise type that returns suspend_always starts lazily: the body runs nothing until the first resume. The same generator shape, with the same loop, behaves both ways. Only the promise type differs.

The program below builds both shapes from one template. The template parameter selects the start: true gives suspend_never, false gives suspend_always. Each generator yields the squares 0, 1, and 4. The main function creates the eager generator first, then the lazy one, then iterates both and adds the values.

C++
// Pitfall 1: initial_suspend decides WHEN the body first runs.
// EagerGen (suspend_never) runs its body at creation; LazyGen (suspend_always) waits.
#include <coroutine>
#include <iostream>
#include <optional>
template <typename T, bool Eager>
struct Gen {
    struct promise_type {
        std::optional<T> value;
        Gen get_return_object() { return Gen{std::coroutine_handle<promise_type>::from_promise(*this)}; }
        auto initial_suspend() noexcept {
            if constexpr (Eager) return std::suspend_never{};
            else return std::suspend_always{};
        }
        std::suspend_always final_suspend() noexcept { return {}; }
        std::suspend_always yield_value(T v) noexcept { value = v; return {}; }
        void return_void() noexcept {}
        void unhandled_exception() { std::terminate(); }
    };
    std::coroutine_handle<promise_type> h;
    explicit Gen(std::coroutine_handle<promise_type> hh) : h(hh) {}
    ~Gen() { if (h) h.destroy(); }
    Gen(const Gen&) = delete; Gen& operator=(const Gen&) = delete;
    Gen(Gen&& o) noexcept : h(o.h) { o.h = {}; }
    struct Iter {
        std::coroutine_handle<promise_type> h;
        bool done = false;
        Iter& operator++() { h.resume(); done = h.done(); return *this; }
        T operator*() const { return *h.promise().value; }
        bool operator!=(const Iter& o) const { return done != o.done; }
    };
    Iter begin() { if constexpr (!Eager) h.resume(); return Iter{h, h.done()}; }
    Iter end() { return Iter{h, true}; }
};
Gen<int, true> eager_squares() {
    std::cout << "eager body: running before first yield\n";
    for (int i = 0; i < 3; ++i) co_yield i * i;
}
Gen<int, false> lazy_squares() {
    std::cout << "lazy body: running before first yield\n";
    for (int i = 0; i < 3; ++i) co_yield i * i;
}
int main() {
    std::cout << "creating eager generator...\n";
    auto e = eager_squares();
    std::cout << "eager generator created\n";
    std::cout << "creating lazy generator...\n";
    auto l = lazy_squares();
    std::cout << "lazy generator created\n";
    int sum = 0;
    for (int v : e) sum += v;
    for (int v : l) sum += v;
    std::cout << "pit-eager-ok " << sum << "\n";
    return sum == 10 ? 0 : 1;
}

The output, identical on GCC 13.3.0, GCC 16.2.0, and Clang 18.1.3:

Output
creating eager generator...
eager body: running before first yield
eager generator created
creating lazy generator...
lazy generator created
lazy body: running before first yield
pit-eager-ok 10

Read the order of the lines. The eager body prints between the two creation lines: the body ran during the call to eager_squares, before the generator object was even assigned. The lazy body prints only after the second creation line, at the first iteration of the loop. The sum is 10 because each generator yields 0, 1, and 4, which sum to 5, and two generators give 10.

What the output proves: eager and lazy are properties of the promise type, not of the coroutine. A claim about when a generator body runs that does not name the promise type is wrong for one of the two shapes. The companion guide states the same rule in one sentence; this fixture is the executed proof of it.

Fixture 2: the frame is destroyed when the generator is destroyed

A coroutine frame holds the local variables of the coroutine body. When the generator that owns the frame is destroyed mid-iteration, the frame is destroyed at that moment, and everything in it is released then. The loop does not finish first. The values that were never pulled are never computed.

The program below puts a guard object inside the coroutine body. The guard prints when it is constructed and when it is destroyed. The main function pulls one value, then lets the generator go out of scope. The generator yields 0, 1, 2, 3, and 4 if iterated to the end. Only the first value is pulled.

C++
// Pitfall 2: destroying a generator mid-iteration destroys the coroutine frame
// (and everything in it) right then — not when the loop "would have" finished.
#include <coroutine>
#include <iostream>
#include <optional>
struct Guard {
    Guard() { std::cout << "guard: acquired in coroutine frame\n"; }
    ~Guard() { std::cout << "guard: destroyed with the frame\n"; }
};
template <typename T>
struct Gen {
    struct promise_type {
        std::optional<T> value;
        Gen get_return_object() { return Gen{std::coroutine_handle<promise_type>::from_promise(*this)}; }
        std::suspend_always initial_suspend() noexcept { return {}; }
        std::suspend_always final_suspend() noexcept { return {}; }
        std::suspend_always yield_value(T v) noexcept { value = v; return {}; }
        void return_void() noexcept {}
        void unhandled_exception() { std::terminate(); }
    };
    std::coroutine_handle<promise_type> h;
    explicit Gen(std::coroutine_handle<promise_type> hh) : h(hh) {}
    ~Gen() { if (h) h.destroy(); }
    Gen(const Gen&) = delete; Gen& operator=(const Gen&) = delete;
    Gen(Gen&& o) noexcept : h(o.h) { o.h = {}; }
    struct Iter {
        std::coroutine_handle<promise_type> h;
        bool done = false;
        Iter& operator++() { h.resume(); done = h.done(); return *this; }
        T operator*() const { return *h.promise().value; }
        bool operator!=(const Iter& o) const { return done != o.done; }
    };
    Iter begin() { h.resume(); return Iter{h, h.done()}; }
    Iter end() { return Iter{h, true}; }
};
Gen<int> counted() {
    Guard g;
    for (int i = 0; i < 5; ++i) co_yield i;
}
int main() {
    {
        auto gen = counted();
        auto it = gen.begin();
        std::cout << "first value: " << *it << "\n";
        std::cout << "destroying generator after one pull...\n";
    }
    std::cout << "generator gone; loop never finished\n";
    std::cout << "pit-destroy-ok\n";
    return 0;
}

The output, identical on GCC 13.3.0, GCC 16.2.0, and Clang 18.1.3:

Output
guard: acquired in coroutine frame
first value: 0
destroying generator after one pull...
guard: destroyed with the frame
generator gone; loop never finished
pit-destroy-ok

Read the order of the lines. The guard is destroyed immediately when the generator goes out of scope, before the line that says the generator is gone. The loop never reaches 1, 2, 3, or 4. The guard print is the observation: a resource held in a coroutine frame — a lock, a file handle, a connection — is released the moment the generator is destroyed mid-iteration, not when the loop would have finished. Code that breaks out of a generator loop early must expect that release to have happened already.

The companion guide states that the generator owns the frame and that the destructor destroys it. This fixture shows the timing: the destruction happens at the point the generator is destroyed, with a visible side effect inside the frame.

Fixture 3: a lazy task runs nothing until resumed

A task with suspend_always as its initial_suspend runs none of its body at creation. The body, including any side effect in it, runs only after an explicit resume. Create the task and forget to resume it, and the body never executes at all. There is no error and no warning. The program simply never does the work.

The program below is the smallest shape that shows it. The task body prints one line. The main function creates the task, prints that the body has not run yet, resumes the task, and checks that it is done.

C++
// Pitfall 3: a lazy task runs NOTHING until resumed — create it, forget to
// resume it, and its body (including side effects) never executes at all.
#include <coroutine>
#include <iostream>
struct Task {
    struct promise_type {
        Task get_return_object() { return Task{std::coroutine_handle<promise_type>::from_promise(*this)}; }
        std::suspend_always initial_suspend() noexcept { return {}; }
        std::suspend_always final_suspend() noexcept { return {}; }
        void return_void() noexcept {}
        void unhandled_exception() { std::terminate(); }
    };
    std::coroutine_handle<promise_type> h;
    explicit Task(std::coroutine_handle<promise_type> hh) : h(hh) {}
    ~Task() { if (h) h.destroy(); }
    Task(const Task&) = delete; Task& operator=(const Task&) = delete;
    Task(Task&& o) noexcept : h(o.h) { o.h = {}; }
    void resume() { if (h && !h.done()) h.resume(); }
    bool done() const { return !h || h.done(); }
};
Task work() {
    std::cout << "task body: running (this prints only after a resume)\n";
    co_return;
}
int main() {
    std::cout << "creating task...\n";
    Task t = work();
    std::cout << "task created; body has NOT run yet\n";
    std::cout << "resuming task...\n";
    t.resume();
    std::cout << "task done: " << (t.done() ? "yes" : "no") << "\n";
    std::cout << "pit-lazy-ok\n";
    return t.done() ? 0 : 1;
}

The output, identical on GCC 13.3.0, GCC 16.2.0, and Clang 18.1.3:

Output
creating task...
task created; body has NOT run yet
resuming task...
task body: running (this prints only after a resume)
task done: yes
pit-lazy-ok

The task body prints only after the resume line. Between creation and resume, the program prints nothing from the body. The done check reads yes after the resume. The companion guide builds a task of this shape and states that the body runs only when the caller resumes it; this fixture is the executed proof, with the failure mode spelled out: a forgotten resume is silent, and the side effect never happens.

What this guide does not cover

Symmetric transfer and the ordering of suspension points in co_await were not probed, and this guide claims nothing about them. The trap where final_suspend returns suspend_never and the frame is destroyed twice is covered in the companion guide, C++20 Coroutines to C++23 std::generator, and is not repeated here: every fixture in this tutorial suspends at the final point. The standard generator type, std::generator, is also covered there, not here. MSVC, libc++, and GCC 15 were not tested, and no result from another compiler, library, or platform is claimed.

Checklist

  • Before assuming when a generator body runs, check what initial_suspend returns in the promise type: suspend_never runs the body at creation, suspend_always waits for the first resume.
  • Before breaking out of a generator loop early, decide what the early exit releases: everything held in the frame is destroyed when the generator is destroyed.
  • Before relying on a lazy task side effect, resume the task: creation alone runs nothing, and a forgotten resume fails silently.

Sources

  • cppreference, Coroutines (C++20) — the start rule: initial_suspend returns suspend_always for lazily-started coroutines or suspend_never for eagerly-started coroutines, and the body starts when the co_await on it resumes; the coroutine state holds the promise object, the parameter copies, and the locals whose lifetime spans a suspension point; destroying the state through the handle ends the coroutine.
  • Veldica, C++20 Coroutines to C++23 std::generator — the framework this guide points at: the hand-rolled promise type, task, and generator, the one-sentence eager and lazy rule this guide executes, and the final-suspend double-destroy trap this guide does not repeat.

Keep Exploring