boostorg / cobalt

Coroutines for C++20 & asio
https://www.boost.org/doc/libs/master/libs/cobalt/doc/html/index.html
191 stars 22 forks source link

co_yield in for loop not incrementing index var. #188

Closed kilasuelika closed 5 days ago

kilasuelika commented 6 days ago

Following code:

#include <boost/cobalt.hpp>
#include <iostream>
#include <optional>

using namespace boost;

cobalt::generator<std::optional<int>> next(int k) {
    for (int i = 0; i < k; ++i) {
        std::println(std::cout, "getting {}", i);
        co_yield i;
    }
    co_return{};
}

cobalt::main co_main(int argc, char* argv[]) {
    while (auto x = co_await next(5)) {
        std::println(std::cout, "got {}", x.value());
    }
    co_return 0;
}

In my MSVC, the console keeps showing "getting 0" and never finished. Seems the i is not incremented. Is this a desired behavior?

klemens-morgenstern commented 5 days ago

Yes, because you are creating a new generator when you call next(5) and then destroying it rightaway.

cobalt::main co_main(int argc, char* argv[]) {
    auto g = next(5);
    while (auto x = co_await  g) {
        std::println(std::cout, "got {}", x.value());
    }
    co_return 0;
}

That should do it.