7 ms·
C++ Lambdas are capturing, so they aren't plain old functions. They evaluate to closures: function + environment. In C++ the captured environment is explicitly
by rnvannatta 5y ago
C++ Lambdas are capturing, so they aren't plain old functions. They evaluate to closures: function + environment. In C++ the captured environment is explicitly written in the [] section of the lambda.
The issue that I think the top comment is alluding to is that lambdas cannot capture by reference and then return, due to that stack frame becoming invalidated, which is a fairly large limitation that prevents swaths of lambda heavy code from working.
I personally think that this is a fine tradeoff for what C++ is: there's still plenty of utility in lambdas for simple higher order functions like maps and filters.
- flqn 5y agoA c++ lambda is a struct with a call operator. The destructors of captured objects are appropriately called when the lambda's lifetime ends. Managing the lifetime of referenced objects is something you always have to worry about in c++ anyway, lambdas don't change that.
- usefulcat 5y agoI feel like some people may be assuming that a capturing lambda must necessarily dynamically allocate memory, and that's just not always true. The large majority of lambdas that I have written in c++ didn't need to do any dynamic allocation because they were used in (and only in) the scope where they were defined. Most of the time the compiler probably just inlined them.
- int_19h 5y agoAlthough this kind of code is also exactly where Rust shines because ownership is explicit throughout, so you can't just accidentally forget that you captured something byref.
- a_t48 5y agoBut hold up - capturing a stack variable by reference in a lambda isn't defined behavior - it will be garbage later when you try to read from it.
- slavik81 5y agoIf your lambda doesn't capture any variables, it can be converted to a function pointer. You can also just capture by value, rather than by reference. If you really want, there's also reference counting with shared_ptr.
- jhgb 5y ago> You can also just capture by value, rather than by reference. Those things are misnomers anyway. Having access to an enclosing environment via a free variable in a lambda expression is completely orthogonal to values vs. references. I suspect they should have named the whole thing differently.