Skip to content

std::generator (C++23)

One-Liner

A coroutine generator that lazily produces a sequence of values—replaces hand-written iterators, features zero heap allocation (customizable allocator), and reduces code volume by an order of magnitude.

#include <generator>

Core API Cheat Sheet

OperationSignatureDescription
Generator Typetemplate<class T> class generatorLazy value sequence, satisfies the view concept
Yield Valueco_yield expr;Yields a value and suspends
Finish Generationco_return;Ends the generator
Iterationgenerator::iteratorInput iterator, for range-for loops
Range AdaptationDirectly usable in ranges:: pipelinesGenerator is a view, composable
Reference Typegenerator<const T&>Yield by reference (avoid copies)
Allocatortemplate<class T, class Alloc> class generatorCustomizable coroutine frame allocator

Minimal Example

cpp
// 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: Computes the next value only when needed, without pre-allocating memory for the entire sequence.
  • Coroutine frames can use custom allocators, suitable for static memory pools.
  • Replaces hand-written iterators and callback functions, significantly improving code readability.
  • C++23 feature; compiler support is still ongoing (GCC 14+, Clang 17+, MSVC 19.34+).
  • Generator lifetime management requires attention: accessing yielded values after the generator is destroyed is undefined behavior.

Compiler Support

GCCClangMSVC
141719.34

See Also


部分内容参考自 cppreference.com,采用 CC-BY-SA 4.0 许可

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05