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:
- https://en.cppreference.com/w/cpp/coroutine/coroutine_handle (Thanks 463035818_is_not_a_number)
- The C++20 standard also mentions it in 9.5.4.10 Example 2 (checked on N4892).
- (German) https://www.heise.de/developer/artikel/Ein-unendlicher-Datenstrom-dank-Coroutinen-in-C-20-5991142.html
- https://www.scs.stanford.edu/~dm/blog/c++-coroutines.html - Mentiones that it would leak if it weren't called, but does not cite a passage from the standard or why it isn't called in the destructor of
std::coroutine_handle
.