1

James McNellis 在他的演讲“C++ 协程简介”(https://youtu.be/ZTqHjjm86Bw?t=1898)中说:

协程在以下情况下被销毁:

  • final_suspend 恢复,
  • coroutine_handle<>::destroy() 被调用,

以先发生者为准。

在我的测试中,我看到(VS 2015,VS 2017 RC),恢复在 final_suspend 上暂停的协程反而会导致错误:

Awaits2017.exe 中 0x010B9EDD 处未处理的异常:RangeChecks 检测代码检测到超出范围的数组访问。发生了

有什么想法可能会在这里发生吗?

#include <experimental/resumable>

using namespace std;
using namespace std::experimental;

struct Coro
{
    coroutine_handle<> m_coro;
    Coro(coroutine_handle<> coro) : m_coro(coro) {}

    struct promise_type
    {
        Coro get_return_object()
        {
            return Coro(coroutine_handle<promise_type>::from_promise(*this));
        }

        auto initial_suspend() { return false; }
        auto final_suspend() { return true; }
        void return_void() {}
    };
};

Coro simple()
{
    co_return;
}

int main()
{
    Coro c = simple();
    c.m_coro.resume(); // runtime error here
}
4

1 回答 1

2

经验法则:

  • 如果final_suspend返回true,您应该调用coroutine_handle<>::destroy(),而不是resume().

  • 如果final_suspend返回false,你也不应该调用destroy(),协程会自行清理。

请注意,VS 2015 中包含的协程不是 James McNellis 在视频中展示的(提案有很多修改),说明:

final_suspend 恢复

可能会令人困惑。它并不真正意味着resume()被称为。

于 2016-11-29T14:08:27.043 回答