C++20 Coroutines: Unexpected Behavior When Awaiting Future Result
I'm experiencing unexpected behavior when using C++20 coroutines to await a `std::future`. The coroutine seems to be completing without waiting for the future to become ready, leading to premature execution of subsequent code. Hereβs a simplified version of what Iβm working with: ```cpp #include <iostream> #include <future> #include <coroutine> struct Awaiter { std::future<int> fut; bool await_ready() { return fut._Ready(); } // Simplified example void await_suspend(std::coroutine_handle<> handle) { // Normally, I'd set up a callback to resume the coroutine when ready } int await_resume() { return fut.get(); } }; awaitable<int> asyncFunction() { std::future<int> fut = std::async([] { std::this_thread::sleep_for(std::chrono::seconds(1)); return 42; }); co_await Awaiter{fut}; std::cout << "Value: " << co_await Awaiter{fut} << '\n'; // This line executes too early } int main() { auto result = asyncFunction(); // Code to wait for the coroutine to complete } ``` In this example, I expect the coroutine to suspend until the future is ready, but it appears that the line that prints the value is executing immediately after the `co_await`, causing it to output an uninitialized value. I've checked that the future is indeed valid and not set to ready before the `await_suspend` is called. I've tried implementing a custom `await_ready` function to ensure the coroutine checks if the future is ready before proceeding, but it still behaves unexpectedly. The output is just a random value or sometimes even crashes. How can I correctly await a `std::future` in a coroutine? Is there a better way to work with futures in C++20 coroutines that I might be missing?