当我不需要返回任何东西时,“co_return”应该做什么?

Dav*_*aim 5 c++ c++20 c++-coroutine

我有一个具体的用例:

在我的库concurrencppmake_exceptional_lazy_result中,我想实现基本上类似于 C# 方法的功能Task.FromException

在这个函数的实现内部,我总是会抛出异常,我永远不会得到co_return有效的对象。

我当前的实现如下所示:

template<class type, class exception_type>
lazy_result<type> make_exceptional_lazy_result(exception_type exception) {
    throw exception;
    co_return *static_cast<type*>(std::malloc(sizeof(type)));
}
Run Code Online (Sandbox Code Playgroud)

我对黑客行为感到恶心malloc——一方面,我必须做点什么co_return,另一方面,程序永远不会真正到达这条线。

我可以做得更好吗?我担心返回对未初始化的本地内存的引用(我不知道根据语言是否可以)。

我还可以在这里做哪些看起来更好的其他选择?请注意,它type不一定是默认可构造的,因此返回 atype{}不是一个选项。

Cal*_*eth 2

您可以编写自己的可等待类型,该类型在 ed 时抛出异常co_await

template<class type, class exception_type>
lazy_result<type> make_exceptional_lazy_result(exception_type exception) {
    struct awaitable {
        exception_type exception;
        bool await_ready() { return true; }
        void await_suspend(std::coroutine_handle<> h)
        {}
        void await_resume() 
        {
            throw exception;
        }
    };
    co_await awaitable{ exception };
}
Run Code Online (Sandbox Code Playgroud)

  • 您应该让 `await_ready()` 返回 `true` 并从 `await_resume()` 中抛出。这完全避免了暂停,并避免了[标准中奇怪的极端情况](https://timsong-cpp.github.io/cppwp/expr.await#5.1.3)关于从`await_suspend()`抛出绕过`等待恢复()`。 (3认同)