I am starting with c++ coroutines and I have an implementation of a generator. It works fine, but I am worried about lifetimes. Specifically I saw warnings about not using captures in lambdas for coroutines because at the first suspension point the lambda will be destroyed and the captured data will not exist anymore. Also C++ guidelines:"CP.53: Parameters to coroutines should not be passed by reference". What about this code:
std::string get_string();
MyGenerator<char> iterate_string(std::string_view sv)
{
for (auto c : sv)
co_yield c;
}
void do_something()
{
for (auto c : iterate_string(get_string())
std::cout << c;
}
I am passing (well, creating) a value of string_view; but that in itself is only a reference to a temporary std::string.
Is "iterate_string" safe? I think it is, the ranged for-loop is responsible for the lifetime; but I also wouldn't have expected problems using captures in a lambda coroutine.