CppCoroutines icon indicating copy to clipboard operation
CppCoroutines copied to clipboard

03 中对右值 Generator 进行函数式变换析构的问题

Open ywnkm opened this issue 1 year ago • 2 comments

Generator<int> generator = Generator<int>::from(1, 2, 3, 4).map([](int i) {
    return i * 2;
});

在这个例子中,由 from 生成的对象在对 generator 消费前已经析构掉了,导致后续出错

我有几个思路。

1. 使用 c++23 的 deducing this. 把原map函数限定为左值引用,然后添加一个值传递的重载

template<typename F>
Generator<std::invoke_result_t<F, T>> map(F f) & {
    while (has_next()) {
        co_yield f(next());
    }
}

template<typename F>
Generator<std::invoke_result_t<F, T>> map(this auto self, F f) {
    while(self.has_next()) {
        co_yield f(self.next());
    }
}

但是这个语法目前只有 msvc 实现了

2. 在map的右值引用版本中把原 Generator 复制一份

template<typename F>
Generator<std::invoke_result_t<F, T>> map(F f) & {
    while (has_next()) {
        co_yield f(next());
    }
}


template<typename F>
auto map(F f) && {
    return [&f](Generator<T> generator) -> Generator<std::invoke_result_t<F, T>> {
        while(generator.has_next()) {
            co_yield f(generator.next());
        }
    }(std::move(*this));
}

ywnkm avatar Mar 31 '23 05:03 ywnkm

我也遇到了这个问题。

1和2感觉都是通过把generator复制一份来解决,请问Generator复制的代价大么,可以用指针解决复制的问题么?

xzxxzx401 avatar Apr 03 '23 07:04 xzxxzx401

这个问题是个已知问题,不过一直没空研究,等我有空了看看。复制的成本应该不大,不过得确认下复制会不会引发别的问题

bennyhuo avatar Apr 03 '23 08:04 bennyhuo

这个问题之前就解决了,然而忘了提交。。。关键问题是每一个 Generator 的实例对应一个协程,消费的话也需要把所有权移走,只要保证每次都是移动到新的 Generator 当中就可以了。

bennyhuo avatar Jul 20 '24 15:07 bennyhuo