I know that if co_return (implicit or explicit) is reached.
co_await promise.final_suspend()
is called.
In final_suspend() one can definetly call handle.destroy() which to my understanding destruct all the object in coroutine frame (CF), lastly calls ~promise_type(), then it frees the allocated CF. See below Lewis Baker recommends this.
However:
-
If final_suspend() does not call handle.destroy() or returns std::suspend_never or , will CF be destroyed properly right after
co_await promise.final_suspend()
completes? -
What happens if final_suspend() returns std::suspend_always ?
-
Is freeing CF somehow tied to the compiler deduced destructor of ~promise_type() ?
*Lewis Baker recommends this here: https://lewissbaker.github.io/2018/09/05/understanding-the-promise-type
Note that while it is allowed to have a coroutine not suspend at the final_suspend point, it is recommended that you structure your coroutines so that they do suspend at final_suspend where possible. This is because this forces you to call .destroy() on the coroutine from outside of the coroutine (typically from some RAII object destructor) and this makes it much easier for the compiler to determine when the scope of the lifetime of the coroutine-frame is nested inside the caller. This in turn makes it much more likely that the compiler can elide the memory allocation of the coroutine frame.
Read a lot.
Also, read the comments to this blig here:
https://dev.to/atimin/the-simplest-example-of-coroutines-in-c20-4l7a