为什么协程类型必须移动可构造?

时间:2018-04-09 05:03:15

标签: c++ visual-c++ language-lawyer c++17 c++-coroutine

[这特定于TS协程,VC ++ 17及更高版本。不重复。 ]

我正在试验实验协同程序。我定义了一个名为“resumable_thing”的协程类型(它基于McNellis在2016年的演讲。目前,它已演变成一个原始的单细胞生成器。)除非是复制构造函数或者类型,否则该类型不会编译定义了一个move-constructor,尽管事实上永远不能调用ctor?

为什么?

#include <iostream>
#include <experimental/coroutine>
#include <experimental/generator>

using namespace std;
using namespace experimental;
template<class T>
struct resumable_thing {
    struct promise_type {
        T _value;
        resumable_thing get_return_object() {
            return resumable_thing(coroutine_handle<promise_type>::from_promise(*this));
        }
        auto initial_suspend() { return suspend_always{}; }
        auto final_suspend() { return suspend_always{}; }
        void return_value(const T& value) {_value = value; }        
        void yield_value(const T&v) { return_value(v); }
    };

    coroutine_handle<promise_type> _coroutine;

    // ???? Why must I define this? ????
    resumable_thing(resumable_thing &&other) {
        assert(false);
        _coroutine = std::move(other._coroutine);
        other._coroutine = nullptr;
    }
    // Member functions 
    void resume() { _coroutine.resume(); }
    auto get() {return _coroutine.promise()._value;}
    auto operator() () { resume(); return get(); }

    // Ctors dtors
    resumable_thing(resumable_thing const&) = delete; 
    resumable_thing& operator=(resumable_thing const&) = delete;
    resumable_thing() = default;

    explicit resumable_thing(coroutine_handle<promise_type> coroutine)
        : _coroutine(coroutine)
    {}

    ~resumable_thing() { if (_coroutine) _coroutine.destroy(); }



};

static
resumable_thing<int> take_five() {
    for (int i = 0; i<5 ; ++i) {
        co_yield i;
    }
    co_return -1;
}

int main() {    
    auto count = take_five();
    for (int i = count(); i >= 0; i=count()) {
        cout << i << '\n';
    }
    return 0;
}

稍后添加。我还是不知道为什么VC ++会抱怨。无论如何,很清楚推动者应该做什么,如果他们做了什么,那就是:

resumable_thing(resumable_thing &&right_) 
    : coroutine_(right_.coroutine_)
{
    right_.coroutine_ = nullptr;
}

resumable_thing &operator=(resumable_thing &&right_)
{
    if (this != std::addressof(right_)) {
        coroutine_ = right_.coroutine_;
        right_.coroutine_= nullptr;
    }
    return *this;
}

0 个答案:

没有答案
相关问题