Implementing a Simple Generator
Build a generator coroutine that lazily yields values.
Implementing a Simple Generator is a free C++ Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Generators as Coroutines
A generator is a coroutine that yields values one at a time. Each call to the generator produces the next value and suspends.
The Generator Type
Define a class with a nested promise_type. The compiler uses it to manage the coroutine s state.
template <typename T>
struct Generator {
struct promise_type {
T current_value;
Generator get_return_object() {
return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_void() {}
std::suspend_always yield_value(T value) {
current_value = value;
return {};
}
void unhandled_exception() { std::terminate(); }
};
std::coroutine_handle<promise_type> h;
// ... constructors, destructor, next() ...
};Using the Generator
Once defined, generators feel like Python yield.
Generator<int> counting() {
int n = 0;
while (true) co_yield n++;
}
auto g = counting();
for (int i = 0; i < 5; ++i) {
std::cout << g.next() << " ";
}
// 0 1 2 3 4coroutine_handle
The compiler returns a std::coroutine_handle. It represents the suspended coroutine — you can resume(), destroy(), or check done().
Suspension Points
Each co_yield suspends. When the caller calls resume(), execution continues until the next suspension or the end of the coroutine.
initial_suspend and final_suspend
Two customization points:
initial_suspend— returnsuspend_alwaysfor a lazy start;suspend_neverfor eagerfinal_suspend— controls cleanup. Usuallysuspend_alwaysfor proper destruction
C++23 std::generator
C++23 added std::generator in <generator>. You no longer need to hand-roll the type for the common case.
#include <generator>
std::generator<int> counting() {
int n = 0;
while (true) co_yield n++;
}Range-Based for
If the generator type supports begin/end, range-based for just works.
for (int x : counting()) {
if (x >= 10) break;
std::cout << x;
}Pull vs Push Semantics
Generators are pull-based — the caller drives the iteration. Push-based coroutines are async tasks.
Use Cases
Generators are great for:
- Lazy sequences (Fibonacci, primes, line-by-line file readers)
- Streaming data without materialization
- Iterating tree-like structures
Memory Considerations
The coroutine frame is allocated on the heap by default. The compiler may elide the allocation when inlining permits — measure when performance matters.
Libraries to Explore
For learning, cppcoro by Lewis Baker has well-documented generator and task types. Boost.Asio provides coroutine-friendly I/O. C++23 onwards adds standard library support.
Quick Check
What is the C++23 standard library type for generator coroutines?
Recap
A generator coroutine yields values lazily with co_yield. Implement it with a class containing a promise_type. C++23 standardized std::generator. Generators excel at lazy sequences and streaming.
Frequently asked questions
Is the “Implementing a Simple Generator” lesson free?
Yes — the full text of “Implementing a Simple Generator” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.
What will I learn in “Implementing a Simple Generator”?
Build a generator coroutine that lazily yields values. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C++ Academy?
No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Implementing a Simple Generator” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C++ Academy lesson?
Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Coroutine Concepts co_await co_yield co_return
- Implementing a Simple Generator
- Async Tasks and Awaiter Types
- Coroutine Frame Allocation