Advertisement
Intermediate C++, Coroutines

What is a generator and how do coroutines implement one?

Short answer

A generator is a function producing a sequence of values lazily, one at a time, on demand. With coroutines, co_yield suspends and hands back a value each time the consumer asks for the next, resuming where it left off.

Save C++ mock interview
Advertisement
AModel answer
A generator is a function producing a sequence of values lazily, one at a time, on demand. With coroutines, co_yield suspends and hands back a value each time the consumer asks for the next, resuming where it left off. This avoids computing or storing the whole sequence, enabling infinite or expensive sequences to be consumed incrementally.
Generator<int> fib() {
    int a=0,b=1;
    while (true) { co_yield a; auto t=a; a=b; b=t+b; }
}
Real-world example
An infinite Fibonacci generator yields numbers lazily so the consumer takes only as many as needed.
Likely follow-ups
  • Why is a generator memory-efficient? | Which keyword yields values?
Related topics