2 ms·
I don't dislike all lambdas. I just wrote some code that made pretty heavy use of lambdas, but they were always called synchronously within their creating funct
by notacoward 6y ago
I don't dislike all lambdas. I just wrote some code that made pretty heavy use of lambdas, but they were always called synchronously within their creating function, as a way to reduce code duplication within that function. Sure, I could have defined a separate method, with a separate declaration in the header file, with lots of arguments, but that would have been considerably less readable.
What I often find problematic is lambdas that outlive their creators. Especially ones that have lots of captures. Especially especially ones where those captures include objects with complex destructors. It's a common pattern in the code I have to work with, and it constantly results in serious bugs. A far better pattern is to wrap the things that need to outlive the caller in their own object - often a "request" object that should have already existed and had its own separate lifetime - and pass that around instead of passing lambdas.
I'd be perfectly happy with lambdas, even lambdas with captures, that couldn't outlive their creator. Trying to attach one to an object with non-local scope would be a compiler error. We already have objects to wrap up the same bits of data and control flow that a long-lived lambda would have. People should use them.