does the life of the automatic get extended to the life of the lambda function?
No. The lambda might be confusing here, so let's rewrite it to be a struct:
struct X
{
int operator()() const { return ref++; }
int& ref;
};
auto genfunc (int start)
{
int count=start;
return X{count};
}
The X
object that we created holds a reference (ref
) to a temporary (count
) that goes out of scope as soon as the object is returned. There's nothing special about the lambda - a dangling reference is a dangling reference.
There's no reason to keep the reference though, just capture by-value:
auto genfunc (int start)
{
return [start]() mutable {
return start++;
};
}
Note the required mutable
keyword.