C++-Coroutine-Zerstörungsreihenfolge
Posted: 03 Jan 2025, 17:58
In diesem Artikel wird dieser Pseudocode für die Transformation einer Coroutine-Funktion durch den Compiler vorgestellt:
Dieser Pseudocode würde jedoch bedeuten, dass, wenn Ihr Coroutine-Typ eine Fortsetzung von final_suspend zurückgibt, der Speicher der Coroutine, die gerade beendet wurde, erst nach freigegeben wird. em> Die Fortsetzung läuft, was alles andere als ideal erscheint. Wenn ich versuche, dieses Minimalbeispiel auszuführen, scheint es vorher zu passieren:
Code: Select all
ReturnType someCoroutine(Parameters parameter)
{
auto* frame = new coroutineFrame(std::forward
(parameters));
auto returnObject = frame->promise.get_return_object();
co_await frame->promise.initial_suspend();
try
{
}
catch (...)
{
frame->promise.unhandled_exception();
}
co_await frame->promise.final_suspend();
delete frame;
return returnObject;
}
Code: Select all
#include
#include
#include
#include
#include
template
class Future;
template
class Future
{
public:
class Awaiter;
class promise_type {
private:
std::exception_ptr _exception;
std::coroutine_handle _continuation;
friend class Awaiter;
public:
Future get_return_object() { return {HandleT::from_promise(*this)}; }
static Future get_return_object_on_allocation_failure() {
abort();
}
// Futures are lazy, they don't do anything until they are
// awaited or a task is spawned that takes one.
std::suspend_always initial_suspend() { return {}; }
// Always cleanup right away. Maybe not the right choice?
std::suspend_never final_suspend() noexcept {
std::cerr