C++20 Coroutines: Unexpected Capture of Local Variables in Lambda Expression
I'm currently experimenting with C++20 coroutines and ran into an scenario where a lambda captures a local variable unexpectedly. The lambda is defined within a coroutine and is supposed to be executed after the coroutine resumes. However, when I run the following code, it seems to capture the variable by value instead of by reference as I intended. Here's a snippet that illustrates the question: ```cpp #include <iostream> #include <coroutine> #include <thread> struct Awaiter { bool await_ready() { return false; } void await_suspend(std::coroutine_handle<> h) { std::this_thread::sleep_for(std::chrono::seconds(1)); h.resume(); } void await_resume() {} }; struct Coroutine { struct promise_type { Coroutine get_return_object() { return Coroutine{}; } std::suspend_always initial_suspend() { return {}; } std::suspend_always final_suspend() noexcept { return {}; } void return_void() {} void unhandled_exception() { std::terminate(); } }; }; Coroutine myCoroutine(int &x) { co_await Awaiter(); auto lambda = [&]() { std::cout << "Value of x: " << x << '\n'; }; lambda(); // Calling lambda here } int main() { int value = 42; myCoroutine(value); value = 100; // Change value after coroutine is started std::this_thread::sleep_for(std::chrono::seconds(2)); // Wait for coroutine to finish return 0; } ``` When I run this code, even though I expect the output to be `Value of x: 100`, it instead prints `Value of x: 42`. It seems that the lambda captures the variable `x` at the time of its definition, not when it's invoked. I've checked that I'm capturing by reference with `[&]`, so Iām confused about how this happened. I also tried replacing the lambda with a regular function to see if it would behave any differently, but the scenario persisted. Is there a way to ensure that the lambda captures the most recent value of `x` when it's executed, or is there something I'm fundamentally misunderstanding about how captures work in coroutines? Any insights would be greatly appreciated!