Skip to content

std::generator (C++23)

In a Nutshell

A coroutine generator that lazily produces value sequences via co_yield -- replaces hand-written iterators, zero heap allocation (allocator-customizable), and reduces code by an order of magnitude.

#include <generator>

Core API Quick Reference

OperationSignatureDescription
Generator typetemplate<class T> class generatorLazy value sequence, satisfies the view concept
Yield valueco_yield expr;Produces a value and suspends
Finish generationco_return;Ends the generator
Iterationgenerator::iteratorInput iterator, for use with range-for
Range adaptationUsable directly in ranges:: pipelinesGenerator is a view, composable
Reference typegenerator<const T&>Yield by reference (avoids 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: Medium

  • Lazy evaluation: computes the next value only when needed, no pre-allocation of the entire sequence's memory
  • Coroutine frames can use custom allocators, suitable for static memory pools
  • Replaces hand-written iterators and callback functions, dramatically improving code readability
  • C++23 feature, compiler support is still advancing (GCC 14+, Clang 17+, MSVC 19.34+)
  • Generator lifetime management requires care: accessing yielded values after the generator is destroyed is undefined behavior

Compiler Support

GCCClangMSVC
141719.34

See Also


Some content adapted from cppreference.com under CC-BY-SA 4.0 license

Built with VitePress