"a coroutine's promise must declare either 'return_value' or 'return_void'" 错误 Visual Studio 2019 C++ 20

"a coroutine's promise must declare either 'return_value' or 'return_void'" Error Visual Studio 2019 C++ 20

VS2019最新c++编译器。

错误是:“协程的承诺必须声明 'return_value' 或 'return_void'”

示例来自 David Mazières https://www.scs.stanford.edu/~dm/blog/c++-coroutines.html 博客 在不同的编译器 GCC 10.2 下工作。

无法获取源码在VS2019中编译

#include <concepts>
#include <coroutine>
#include <exception>
#include <iostream>
struct ReturnObject {
    struct promise_type {
        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 (unsigned i = 0;; ++i) {
        co_await a;
        std::cout << "counter: " << i << std::endl;
    }
}

void
main1()
{
    std::coroutine_handle<> h;
    counter(&h);                
    for (int i = 0; i < 100; ++i) {
        std::cout << "In main1 function\n";
        h();
    }
    h.destroy();
}

我错过了什么? C++ 协程的新手。谁不是?

两个编译器都是正确的。当 promise 类型没有 return_void 时,从协同程序的末尾流出是未定义的行为:

[stmt.return.coroutine]/3:

If p.return_­void() is a valid expression, flowing off the end of a coroutine is equivalent to a co_­return with no operand; otherwise flowing off the end of a coroutine results in undefined behavior.

您可以在 promise 类型中定义一个 noop return_void 以获得您想要的行为:

void return_void() noexcept {}