lewissbaker / cppcoro

A library of C++ coroutine abstractions for the coroutines TS
MIT License
3.43k stars 470 forks source link

Factor out some of the coroutine "ownership" and cleanup code into a common RAII class? #179

Open dschepler opened 4 years ago

dschepler commented 4 years ago

I ended up implementing my own version of a generator template class as an experiment with C++20 coroutines, and then somebody over at codereview.stackexchange.com gave me a link to this project.

It looks like a lot of my implementation is pretty similar to what I saw here. One thing I did differently, though, was to create a class unique_coroutine_handle - heavily inspired by unique_ptr - to abstract out what in the code here is a manual call in the generator destructor.

I found that this made the code probably a bit more readable and maintainable - I no longer needed any custom destructor, move constructor, or move assignment in the generator class; and the compiler was able to deduce on its own that the generator class cannot be copy constructible or copy assignable.

I thought it might also be useful in other classes here. For instance, in the event handlers registered with a scheduler for awaitables such as async_read_operation you might create a capture of a unique_coroutine_handle (and then the lambda destructor would automatically handle cleaning up the coroutine state if the scheduler is stopped early); and the event handler body could include something like handle.release().resume(); . Though these musings come with the caveat that I haven't actually tried implementing anything similar to this part of the library yet.