C++20 coroutine returning `std::optional` causing undefined behavior when used in a loop
I'm not sure how to approach I've looked through the documentation and I'm still confused about I'm working with C++20 and trying to implement a simple coroutine that should return a `std::optional<int>` value..... However, I am running into undefined behavior when I call the coroutine in a loop. The code below demonstrates my approach: ```cpp #include <iostream> #include <coroutine> #include <optional> struct Generator { struct promise_type { std::optional<int> value; 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::exit(1); } auto yield_value(int val) { value = val; return std::suspend_always(); } void return_void() {} }; promise_type *promise; Generator(promise_type *p) : promise(p) {} bool next() { auto result = promise->value; if (promise->initial_suspend().await_ready()) { promise->final_suspend(); return false; } return true; } }; Generator coroutine_example() { for (int i = 0; i < 5; ++i) { co_yield i; } } int main() { auto gen = coroutine_example(); for (int i = 0; i < 5; ++i) { if (gen.next()) { std::cout << "Value: " << *gen.promise->value << '\n'; } } return 0; } ``` When I run this code, I get the output as expected for the first few iterations, but then it seems to crash with an access violation, and the error message is somewhat cryptic. I've tried checking if the coroutine is in a valid state before accessing `promise->value`, but it seems like that doesn't help. Is there a specific problem with how `Generator` is structured or with how I'm accessing `promise->value`? Should I be checking for a valid state after each yield? Any guidance on how to properly manage the coroutine state would be greatly appreciated! I'd really appreciate any guidance on this. I appreciate any insights! I've been using C++ for about a year now. Has anyone dealt with something similar? Has anyone dealt with something similar?