My tutorial and take on C++20 coroutines (2021)
16 days ago
- #C++20
- #Event-Driven Programming
- #Coroutines
- Event-driven code in C++ can be cumbersome due to the need to break code into multiple functions that don't share local variables.
- C++11 improved event-driven coding with lambda expressions, allowing nested lambdas and capturing local variables, but still requires breaking code into many functions.
- C++20 introduces coroutines to simplify writing event-driven code, allowing functions to suspend execution and resume later without sharing a stack.
- The `co_await` operator in C++20 is central to coroutines, enabling suspension and resumption of execution based on awaitable objects.
- Coroutine handles (`std::coroutine_handle`) manage coroutine state and must be manually destroyed to avoid memory leaks.
- The `co_yield` operator simplifies returning values from coroutines by leveraging the promise object's `yield_value` method.
- The `co_return` operator signals the end of a coroutine, with options to return a final value or void, and requires careful handling of coroutine state destruction.
- Exceptions in coroutines are managed via the `unhandled_exception` method in the promise object, allowing exceptions to be re-thrown in the main function.
- A generic generator pattern can be implemented using coroutines to produce values on demand, with proper handling of exceptions and resource cleanup.
- The design of C++20 coroutines is criticized for being overly complex and clunky, particularly around return object handling and undefined behavior when falling off the end of a coroutine.