Skip to content

std::generator (C++23) ​

One-Liner ​

A coroutine generator that lazily produces a sequence of values with co_yield — it replaces hand-written iterators, allocates nothing on the heap (the allocator is customizable), and cuts the amount of code by an order of magnitude.

#include <generator>

Core API Cheat Sheet ​

OperationSignatureDescription
Generator typetemplate<class T> class generatorLazy sequence of values; satisfies the view concept
Yield a valueco_yield expr;Produces a value and suspends
Finish generatingco_return;Ends the generator
Iterationgenerator::iteratorInput iterator, for range-for loops
Range adaptationUsable directly in ranges:: pipelinesA generator is a view, so it composes
Reference typegenerator<const T&>Yields by reference (avoids copies)
Allocatortemplate<class T, class Alloc> class generatorCustomizable allocator for the coroutine frame

Minimal Example ​

C++
// Standard: C++23
#include <generator>
#include <iostream>

std::generator<int> fibonacci() {
    int a = 0, b = 1;
    while (true) {
        co_yield a;
        auto tmp = a;
        a = b;
        b = tmp + b;
    }
}

int main() {
    for (int v : fibonacci() | std::views::take(8)) {
        std::cout << v << " "; // 0 1 1 2 3 5 8 13
    }
}

Embedded Applicability: Moderate ​

  • Lazy evaluation: the next value is computed only when needed, with no memory pre-allocated for the whole sequence
  • The coroutine frame can use a custom allocator, which suits static memory pools
  • Replaces hand-written iterators and callbacks, a big readability win
  • C++23 feature; compiler support is still rolling out (GCC 14+, Clang 17+, MSVC 19.34+)
  • Watch the generator's lifetime: accessing a yielded value after the generator is destroyed is undefined behavior

Compiler Support ​

GCCClangMSVC
141719.34

See Also ​


Some content is referenced from cppreference.com and used under the CC-BY-SA 4.0 license

pdf-latest-4-g85128cc · 85128cc · 2026-10-05