【test.cpp】
#include <coroutine>
#include <iostream>
struct return_object {
struct promise_type {
return_object get_return_object() {
std::cout << "get_return_object" << std::endl;
return_object obj;
obj.that = this;
return obj;
}
std::suspend_never initial_suspend() {
std::cout << "initial_suspend" << std::endl;
std::suspend_never never;
return never;
}
std::suspend_never final_suspend() noexcept {
std::cout << "final_suspend" << std::endl;
std::suspend_never never;
return never;
}
void unhandled_exception() {
std::cout << "unhandled_exception" << std::endl;
}
};
promise_type *that;
};
return_object counter() {
std::cout << "counter begin" << std::endl;
for (int i = 0; i < 2; i++) {
std::suspend_always a;
co_await a;
std::cout << "counter: " << i << std::endl;
}
}
int main()
{
return_object r = counter();
std::coroutine_handle<return_object::promise_type> h = std::coroutine_handle<return_object::promise_type>::from_promise(*r.that);
for (int i = 0; i < 2; i++) {
std::cout << "in main function" << std::endl;
h();
}
return 0;
}
【程序运行结果】
oct1158@oct1158-ubuntu:~/Documents/Code/C/test/coroutine$ ./test
get_return_object
initial_suspend
counter begin
in main function
counter: 0
in main function
counter: 1
final_suspend
oct1158@oct1158-ubuntu:~/Documents/Code/C/test/coroutine$
(因为counter函数执行完毕了,所以h自动销毁了,不用自己调用h.destroy())。