【发布时间】:2021-09-23 16:40:50
【问题描述】:
我是 C++20 协程的新手,很惊讶coroutine_handle::operator bool 在销毁后返回 true?
示例程序:
#include <coroutine>
#include <iostream>
struct ReturnObject {
struct promise_type {
void return_void() {}
ReturnObject get_return_object() { return {}; }
std::suspend_never initial_suspend() { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void unhandled_exception() {}
};
};
struct Awaiter {
std::coroutine_handle<> *hp_;
constexpr bool await_ready() const noexcept { return false; }
void await_suspend(std::coroutine_handle<> h) { *hp_ = h; }
constexpr void await_resume() const noexcept {}
};
ReturnObject
counter(std::coroutine_handle<> *continuation_out)
{
Awaiter a{continuation_out};
for (;;)
co_await a;
}
int main()
{
std::coroutine_handle<> h;
std::cout << "before construction " << (bool)h << '\n';
counter(&h);
std::cout << "after construction " << (bool)h << '\n';
h.destroy();
std::cout << "after destruction " << (bool)h << '\n';
}
https://gcc.godbolt.org/z/a7ehjzhab
打印出来
before construction 0
after construction 1
after destruction 1
为什么销毁后还是返回true?所以无法区分活跃的coroutine_handle 和已破坏的coroutine_handle?
【问题讨论】:
标签: c++ c++-coroutine