【问题标题】:"a coroutine's promise must declare either 'return_value' or 'return_void'" Error Visual Studio 2019 C++ 20“协程的承诺必须声明'return_value'或'return_void'”错误Visual Studio 2019 C++ 20
【发布时间】:2021-07-22 04:05:27
【问题描述】:

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++ 中的协程新手。谁不是?

【问题讨论】:

    标签: c++ visual-studio-2019 c++20 c++-coroutine


    【解决方案1】:

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

    [stmt.return.coroutine]/3:

    如果p.return_­void() 是一个有效的表达式,从协程末尾流出就相当于一个没有操作数的co_­return;否则从协程的末尾流出会导致未定义的行为。

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

    void return_void() noexcept {}
    

    【讨论】:

    • 事实并非如此。即使在协程结束时不存在任何操作数的 co_­return,Visual Studio 也会向您显示错误,但 Promise 中不存在 return_void 方法。
    • @Fedor,这是另一种情况,由[stmt.return.coroutine]/2.2 覆盖。如果你有一个明确的co_return 而没有return_void,编译器需要出错。
    猜你喜欢
    • 2021-09-28
    • 1970-01-01
    • 2020-02-19
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 2019-04-26
    相关资源
    最近更新 更多