Iro*_*net 7 c++ c++20 c++-coroutine visual-studio-2019
VS2019最新的c++编译器。
\n错误是:“协程的承诺必须声明‘return_value’或‘return_void’”
\n从 David Mazi\xc3\xa8res https://www.scs.stanford.edu/~dm/blog/c++-coroutines.html 博客中提取的示例\n在不同的编译器 GCC 10.2 下工作。
\n我无法获取在 VS2019 中编译的源代码。
\n#include <concepts>\n#include <coroutine>\n#include <exception>\n#include <iostream>\nstruct ReturnObject {\n struct promise_type {\n ReturnObject get_return_object() { return {}; }\n std::suspend_never initial_suspend() { return {}; }\n std::suspend_never final_suspend() noexcept { return{}; }\n void unhandled_exception() {}\n \n };\n};\n\nstruct Awaiter {\n std::coroutine_handle<>* hp_;\n constexpr bool await_ready() const noexcept { return false; }\n void await_suspend(std::coroutine_handle<> h) { *hp_ = h; }\n constexpr void await_resume() const noexcept {}\n};\n\nReturnObject\ncounter(std::coroutine_handle<>* continuation_out)\n{\n Awaiter a{ continuation_out };\n for (unsigned i = 0;; ++i) {\n co_await a;\n std::cout << "counter: " << i << std::endl;\n }\n}\n\nvoid\nmain1()\n{\n std::coroutine_handle<> h;\n counter(&h); \n for (int i = 0; i < 100; ++i) {\n std::cout << "In main1 function\\n";\n h();\n }\n h.destroy();\n}\nRun Code Online (Sandbox Code Playgroud)\n我缺少什么?C++ 协程新手。谁不是?
\n两个编译器都是正确的。当 Promise 类型不存在时,从协程的末尾流出return_void是未定义的行为:
\n\n\n\n\n如果
\np.return_\xc2\xadvoid()是一个有效的表达式,则从协程末尾流出相当于co_\xc2\xadreturn没有操作数;否则从协程末尾流出会导致未定义的行为。
您可以在 Promise 类型中定义 noopreturn_void来获取您想要的行为:
void return_void() noexcept {}\nRun Code Online (Sandbox Code Playgroud)\n