coro/corotrace.cpp

The following code example is taken from the book
C++23 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2026
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

#include <iostream>
#include <utility>
#include <generator>
#include "tracingpmr.hpp"

// coroutine using passed memory resource to hold its state:
std::pmr::generator<long> fibonacci(std::allocator_arg_t,
                                    std::pmr::polymorphic_allocator<>,
                                    int num)
{
  // first two numbers are 1:
  long a = 1;
  long b = 1;
  co_yield a;       // SUSPEND with first number
  co_yield b;       // SUSPEND with second number
  // loop over sums of previous two numbers:
  for (int i = 0; i < num-2; ++i) {
    auto sum = a + b;
    co_yield sum;   // SUSPEND with third to num-th number
    a = std::exchange(b, sum);
  }
}


int main()
{
  // init a tracing memory resource:
  TracingPMR pool;
  {
    std::cout << "*** init coroutine:\n";
    auto gen = fibonacci(std::allocator_arg, &pool, 10);

    std::cout << "*** call begin():\n";
    auto pos = gen.begin();

    std::cout << "*** loop with *pos and ++pos:\n";
    while (pos != gen.end()) {
      std::cout << *pos << ' ';
      ++pos;                   // RESUME
    }
    std::cout << '\n';
    
    std::cout << "*** destroy coroutine:\n";
  }
  std::cout << "*** destroy pool\n";
}