cppcoro
cppcoro copied to clipboard
Iterating mutiple times over a generator
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
Shouldn't you have to call the lambda to create the generator?
for (auto i : answer()) { ... }
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 &&" ?).
Ah I didn't see the lambda already being executed on definition, pay no mind to my comment; you're right