C++20 added minimal support for coroutines. They don't fit well into C++ as they don't follow the zero-overhead principle. Calling a coroutine can be expensive with calls to new() and delete(). They were inspired by C# coroutines and are useful for code with concurrency, like handling multiple state machines.
A coroutine is a function that behaves differently on multiple calls, continuing after the last return or co_yield. To implement a coroutine manually in C++, stack variables are turned into member variables of a struct, the function is renamed to resume() and made a member function, a switch/case is added around the function body, and a new case is added for each co_yield. An iterator is added to make the coroutine useful.
However, there are problems. Turning stack variables into struct members can be wasteful on complex functions. The C++ standard hides the coroutine struct behind a pointer and a heap allocation is included with each call to a coroutine. This is hidden even from sizeof(). Inlining is promised to avoid the heap allocation, but it doesn't always work for complex code.
Macros are needed to compose coroutines nicely. Without them, functions like drain_and_yield_all don't work as expected. Coroutines don't compose without macros.
The standard makes co_yield slightly more abstract by using a promise type for communication between the coroutine and the caller. A pointer can be stored in the promise type to avoid copying values. There is also a co_await operator that can be used to access the promise object.
Looking forward to using co_yield and co_await with fibers was disappointing as using the keywords turns a function into a coroutine with heap allocation.
Overall, coroutines exist but are clunky and gross. They worry about inlining and are not ergonomic to use. Suggestions include giving access to the generated struct, thinking about composition, allowing the same operators for fibers, and providing a saner way to access stack variables. It's unclear what coroutines are really for and if they are useful for more than simple generator functions.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。