cppcoro icon indicating copy to clipboard operation
cppcoro copied to clipboard

Iterating mutiple times over a generator

Open ilelann opened this issue 3 years ago • 3 comments

Hello, following code crashes with a SIGSEGV:

        auto answer = []() -> cppcoro::generator<int> {
            co_yield 42;
        }();
        for (auto i : answer) {
            std::cout << i << "\n";
        }
        for (auto i : answer) {
            std::cout << i << "\n";
        }

I guess that iterating twice over a generator is not supported. I am not saying it should be. But if it is not, it is probably worth being documented, and I could not find anything on that.

My setup : Fedora 33, GCC 10, thus with patches from https://github.com/dutow/cppcoro.git I could also reproduce with clang here https://godbolt.org/z/51fxb1

ilelann avatar Oct 01 '20 07:10 ilelann

Shouldn't you have to call the lambda to create the generator? for (auto i : answer()) { ... }

RuthgerD avatar Oct 04 '20 09:10 RuthgerD

Yes it would fix, but that's the point I think is worth being documented. It's not obvious that answer is pointing to dangling data after enumeration, and it goes against intuition on C++ objects lifetime. Furthermore, if dangling status is "by design and not a bug", forcing the user to std::move(answer) might make sense (possibly by constraining begin to "this &&" ?).

ilelann avatar Oct 04 '20 10:10 ilelann

Ah I didn't see the lambda already being executed on definition, pay no mind to my comment; you're right

RuthgerD avatar Oct 04 '20 10:10 RuthgerD