Binding lambda to forwarding reference

111 Views Asked by At

Is it safe to bind to a lambda with auto&&? I.e will the lifetime of the lambda be extended to the lifetime of the forwarding reference? Why / why not?

auto&& fn = <lambda declaration>;

I suspect that it should be. As far as I understand, lambda expressions are supposed to be prvalue expressions, and the auto&& forwarding reference should then become an rvalue reference. rvalue references are supposed to extend the lifetime of temporaries, at least under certain conditions. But here I'm not quite sure if the lambda qualifies.

1

There are 1 best solutions below

4
Amolgorithm On

Short answer. Yes and no.
No, it is not dangerous as you say. Yes, it is safe to bind to a lambda with auto&&, and is not dangerous, because the temporary object isn't destroyed after the end of the definition statement. What happens is that the rvalue reference extends its lifetime (yes like you said) but only until the reference itself gets destroyed, when it is out of scope. So, you are right that it extends the lifetime, but does not do it in such a way that is dangerous.

To quote Scott Meyers, as he elaborates in Effective Modern C++:

The rules for type deduction of auto are the same as those of templates (apart from one exception: curly braces in auto are interpreted as std::initializer_lists).

Also, relating to this matter, declaring a lambda, which is always a pure function, with auto&& is a forwarding reference, thus it is an lvalue reference if initialized from an lvalue and an rvalue reference if initialized from an rvalue. Since lambdas are pure rvalue, it becomes an rvalue reference, which allows it to extend its lifetime but only until the reference itself gets destroyed, when it is out of scope.