General guidelines for defining lambdas
c++, c++11, lambda
Solution
These questions are somewhat subjective, but I'll give it a shot:
Capture by reference when you need to modify the values in the enclosing scope (obviously), or when you want to avoid copying heavy variables; capture by value otherwise.
Capture a specific variable by reference if you need to modify it's value in the enclosing scope, but not the values of other variables.
I try to always specify the return type to increase readability (so other people can immediately know the return type, instead of having to parse the lambda to deduce it).
The last one is the most subjective of all, but I personally think that lambdas bigger than ~3-5 lines should be refactored to functions, because long lambdas can reduce readability. However, there can be many exceptions, so this is rather a matter of personal preference and highly depends on the actual code.
Problem
Now that we're able to use C++11 lambdas in our codebase we're grappling with working out the general principles of how they should be defined and used. I realise that there are certainly subjective elements to this, but I think there are also likely to be some more general rules of thumb that will be useful to the community. What are the general principles of defining a lambda? - When should you prefer to capture by reference `[&]` or value `[=]`? What are the performance implications? - When should you prefer to capture a variable explicitly, eg `[&foo]` ? - Under what circumstances should you specify a return type? (C++14 has better support for inferring return types than C++11) - How complex can a lambda be before it's better being rewritten as a function? Personally, my general principle at the moment is 'Use a lambda whenever you need a simple predicate or comparator', but this may mean I'm missing out on some much more powerful use cases.