Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Concurrency

C++ std::generator class template

Reference for std::generator in C++23: write lazy sequences with co_yield, use them in range-for and views, yield recursively and handle lifetimes.

std::generator<T> (header <generator>, C++23) is the standard coroutine return type for lazy sequences. A function that returns it and uses co_yield produces its values one at a time, only when the caller asks for the next one. Because generator is an input range, you can loop over it with range-for or feed it to range algorithms and views such as std::views::take and std::views::filter.

Generators are ideal for sequences that are infinite, expensive, or too big to store: Fibonacci numbers, lines read from a file, nodes of a tree. The body runs only as far as needed, so an "infinite" loop inside is fine as long as the consumer stops. You need a C++23 compiler and standard library (GCC 14+); our runner supports it.

C++
std::generator<int> count_up(int from) {
    for (int i = from;; ++i) co_yield i;      // infinite, but lazy
}

Try it

C++ Lazy sequences and range adaptors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Recursive yields with elements_of

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
template<class Ref, class V = void, class Allocator = void>
class std::generator;           // also std::pmr::generator<Ref, V>

co_yield value;                                        // yield one element
co_yield std::ranges::elements_of(range_or_generator); // yield every element of a range
Name Description
Ref The reference type produced: generator<int> yields int&& (prvalues), generator<const std::string&> yields references without copying.
V Optional value type. By default it is remove_cvref_t<Ref>.
Allocator Optional allocator for the coroutine frame (void means the default allocator).

Members: begin() (resumes the coroutine to the first co_yield and returns an iterator), end() (a sentinel), and move construction/assignment. A generator is move-only. Its iterator is an input iterator: ++it resumes the coroutine, *it reads the current element.

Errors / undefined behavior: calling begin() more than once is undefined behavior (the sequence is single-pass). An exception thrown in the body is rethrown from begin() or operator++ in the consumer. Using a generator after the objects its parameters refer to are gone is undefined.

Usage notes

  • Single pass. You cannot restart or copy a generator; call the function again for a fresh sequence.
  • Lazy start. Nothing executes until begin() is called, so the work and its side effects happen in the consumer's thread when the loop runs.
  • Reference types. co_yield expr produces a temporary; with generator<const T&> the reference points at an object that lives in the coroutine frame until the next resume. Do not keep it past the next step.
  • Parameters by value. The frame stores copies of by-value parameters. A reference parameter that dangles while the generator still runs is a classic bug, as is a generator whose lambda has captures.
  • Recursion: use co_yield std::ranges::elements_of(g). Hand-written for (auto x : inner) co_yield x; also works but costs a resumption per level for every element.
  • Allocation: each generator allocates a coroutine frame unless the compiler elides it. For hot loops prefer a plain function or a view (std::views::iota) when they are enough.
  • Not for concurrency: a generator is resumed by whoever iterates it; there is no thread involved and no thread safety.
  • Support: <generator> needs -std=c++23 and GCC 14, Clang with libc++ 20+ or a recent MSVC. Older compilers need a third-party library or a hand-written type like the one in Coroutines in practice.
  • Can be composed: generator | views::take(n) stops the underlying coroutine from running further than the n-th element.