The std::coroutine_handle
is an important part of the new coroutines of C++20. Generators for example often (always?) use it. The handle is manually destroyed in the destructor of the coroutine in all examples that I have seen:
struct Generator {
// Other stuff...
std::coroutine_handle<promise_type> ch;
~Generator() {
if (ch) ch.destroy();
}
}
Is this really necessary? If yes, why isn't this already done by the coroutine_handle
, is there a RAII version of the coroutine_handle
that behaves that way, and what would happen if we would omit the destroy
call?
Examples:
std::coroutine_handle
.This is because you want to be able to have a coroutine outlive its handle, a handle should be non-owning. A handle is merely a "view" much like std::string_view -> std::string
. You wouldn't want the std::string
to destruct itself if the std::string_view
goes out of scope.
If you do want this behaviour though, creating your own wrapper around it would be trivial.
That being said, the standard specifies:
The coroutine state is destroyed when control flows off the end of the coroutine or the
destroy
member function([coroutine.handle.resumption])
of a coroutine handle([coroutine.handle])
that refers to the coroutine is invoked.
The coroutine state will clean up after itself after it has finished running and thus it won't leak unless control doesn't flow off the end.
Of course, in the generator case control typically doesn't flow off the end and thus the programmer has to destroy the coroutine manually. Coroutines have multiple uses though and the standard thus can't really unconditionally mandate the handle destructor call destroy()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With