std::noop_coroutine
来自cppreference.com
在标头 <coroutine> 定义 | ||
std::noop_coroutine_handle noop_coroutine()noexcept; | (C++20 起) | |
返回指代无操作协程的协程柄。
若已有无操作协程的协程状态,则 noop_coroutine
的后续调用,是返回先前获得的协程柄,还是指代新的无操作协程的协程状态的协程柄是未指明的。
目录 |
[编辑]参数
(无)
[编辑]返回值
指代无操作协程的 std::noop_coroutine_handle。
[编辑]注解
比较从不同的 noop_coroutine
调用获得的返回值,结果可能相等也可能不相等。
noop_coroutine
可以仅返回指代协程状态对象的 noop_coroutine_handle
而无需开始协程。
[编辑]示例
运行此代码
#include <coroutine>#include <iostream>#include <utility> template<class T>struct task {struct promise_type {auto get_return_object(){return task(std::coroutine_handle<promise_type>::from_promise(*this));}std::suspend_always initial_suspend(){return{};}struct final_awaiter {bool await_ready()noexcept{returnfalse;}void await_resume()noexcept{}std::coroutine_handle<> await_suspend(std::coroutine_handle<promise_type> h)noexcept{// 在当前协程(以 'h' 指代)执行即将结束时调用 final_awaiter::await_suspend。// 若当前协程被另一协程经由 co_await get_task() 恢复,则存储到该协程的柄// 为 h.promise().previous。该情况下,返回柄以恢复先前的协程。// 否则返回 noop_coroutine(),其恢复不做任何事。 if(auto previous = h.promise().previous; previous)return previous;elsereturn std::noop_coroutine();}}; final_awaiter final_suspend()noexcept{return{};}void unhandled_exception(){throw;}void return_value(T value){ result = std::move(value);} T result;std::coroutine_handle<> previous;}; task(std::coroutine_handle<promise_type> h): coro(h){} task(task&& t)= delete; ~task(){ coro.destroy();} struct awaiter {bool await_ready(){returnfalse;} T await_resume(){return std::move(coro.promise().result);}auto await_suspend(std::coroutine_handle<> h){ coro.promise().previous= h;return coro;}std::coroutine_handle<promise_type> coro;}; awaiter operator co_await(){return awaiter{coro};} T operator()(){ coro.resume();return std::move(coro.promise().result);} private:std::coroutine_handle<promise_type> coro;}; task<int> get_random(){std::cout<<"in get_random()\n"; co_return 4;} task<int> test(){ task<int> v = get_random(); task<int> u = get_random();std::cout<<"in test()\n";int x =(co_await v + co_await u); co_return x;} int main(){ task<int> t = test();int result = t();std::cout<< result <<'\n';}
输出:
in test() in get_random() in get_random() 8
[编辑]参阅
(C++20) | 用于无可观察作用的协程 (类) |
(C++20) | std::coroutine_handle<std::noop_coroutine_promise>,有意用于指代无操作协程 (typedef) |