Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to call destroy on a std::coroutine_handle?

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:

  1. https://en.cppreference.com/w/cpp/coroutine/coroutine_handle (Thanks 463035818_is_not_a_number)
  2. The C++20 standard also mentions it in 9.5.4.10 Example 2 (checked on N4892).
  3. (German) https://www.heise.de/developer/artikel/Ein-unendlicher-Datenstrom-dank-Coroutinen-in-C-20-5991142.html
  4. 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.
like image 960
Brotcrunsher Avatar asked Jul 12 '21 19:07

Brotcrunsher


1 Answers

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().

like image 138
Hatted Rooster Avatar answered Oct 21 '22 19:10

Hatted Rooster