CodexBloom - Programming Q&A Platform

C++20 Coroutines: Unexpected Behavior with std::suspend_always in Recursive Coroutine Calls

👀 Views: 90 đŸ’Ŧ Answers: 1 📅 Created: 2025-09-06
c++20 coroutines std::suspend_always C++

I'm wondering if anyone has experience with I'm trying to figure out I've looked through the documentation and I'm still confused about I'm currently working on a project utilizing C++20 coroutines, and I'm encountering unexpected behavior when using `std::suspend_always` in recursive coroutine calls. The goal is to create a coroutine that yields values recursively, but when I attempt to call the coroutine recursively, it seems that the execution doesn't yield as expected. Instead of the expected sequence of values, I am getting only the first value and then the coroutine seems to hang indefinitely. Here's a simplified version of my implementation: ```cpp #include <iostream> #include <coroutine> #include <optional> struct Generator { struct promise_type { auto get_return_object() { return Generator{*this}; } auto initial_suspend() { return std::suspend_always{}; } auto final_suspend() noexcept { return std::suspend_always{}; } void unhandled_exception() { std::terminate(); } std::suspend_always yield_value(int value) { current_value = value; return {}; } int current_value; }; promise_type &promise; Generator(promise_type &p) : promise(p) {} std::optional<int> next() { promise.current_value = 0; if (!promise.final_suspend().await_ready()) { return promise.current_value; } return std::nullopt; } }; Generator recursive_generator(int n) { if (n <= 0) co_return; co_yield n; auto next_gen = recursive_generator(n - 1); while (auto val = next_gen.next()) { co_yield *val; } } int main() { auto gen = recursive_generator(5); while (auto val = gen.next()) { std::cout << *val << " "; } return 0; } ``` When I run this code, I only see the output `5` and then nothing else happens. I expect to yield `5 4 3 2 1` in sequence. I've tried adding debug statements inside the recursive call, but they don't seem to show any execution beyond the first yield. Could there be something wrong with how I manage the coroutine state across recursive calls? I've also considered that it might be an issue with how I'm handling the promise or the suspension, but I'm not sure how to resolve it. Any advice would be greatly appreciated! For context: I'm using C++ on Windows. My development environment is Ubuntu 20.04. Any examples would be super helpful. Thanks for any help you can provide!