C++20 Coroutines with std::optional causing stack overflow in deep recursion
I'm having trouble with I'm sure I'm missing something obvious here, but I'm working on a C++20 project that uses coroutines for asynchronous programming, and I've run into a peculiar scenario..... When I attempt to return a `std::optional` from a coroutine function that is deeply recursive, it leads to a stack overflow behavior. The function is supposed to compute the Fibonacci sequence using coroutines to lazily evaluate the next number in the series. Here's a simplified version of my code: ```cpp #include <iostream> #include <optional> #include <coroutine> std::optional<int> fibonacci(int n) { if (n <= 1) return n; co_return fibonacci(n - 1).value() + fibonacci(n - 2).value(); } int main() { auto result = fibonacci(50); if (result) { std::cout << "Fibonacci(50) = " << *result << '\n'; } else { std::cout << "Failed to compute Fibonacci(50)\n"; } } ``` When I run this code, I get a stack overflow, which I suspect is due to the deep recursion combined with coroutine suspension. I've tried switching the return type to just `int`, but that changes the nature of my function, as I'm trying to leverage `std::optional` to indicate potential failures in computation. I've also looked into using `std::future` or `std::promise`, but they feel heavier for this task. Is there a way to implement this without leading to a stack overflow? Am I misusing coroutines along with `std::optional`, or is there a better approach I can take to achieve laziness without hitting the recursion limit? What's the best practice here? What's the correct way to implement this? I'm working on a web app that needs to handle this. Thanks for any help you can provide! I'm working with C++ in a Docker container on Windows 11. Has anyone else encountered this?