I read this explanations on MSDN pages, for advantages of lambda expression over functor and function pointer. What is meant by ability to ‘retain state’? Is it related to capability to capture some variables by ref or value in enclosing scope?
http://msdn.microsoft.com/en-us/library/dd293608.aspx
When writing code, you probably use function pointers and function
objects to solve problems and perform calculations. Both function
pointers and function objects have advantages and disadvantages:
function pointers involve minimal syntactic overhead, but they do not
retain state within a scope; function objects can maintain state, but
they require the syntactic overhead of a class definition.Lambda expressions are a programming technique that combines the
benefits of function pointers and function objects and that avoids
their disadvantages. Lambda expressions are flexible and can maintain
state, just like function objects, and their compact syntax removes
the need for a class definition, which function objects require.
Lambda expressions enable you to write code that is less cumbersome
and less prone to errors than an equivalent function object.The following examples compare the use of a lambda expression to the
use of a function object. The first example uses a lambda expression
to print to the console whether each element in a vector object is
even or odd. The second example uses a function object to accomplish
the same task.
Could you point at some relevant reference on topics scope, state, maintain state, advantage of lambda expressions?
Functors and lambdas both have this ability over normal functions. It is the ability to remember stuff between function calls. Normal functions have static variables, but those are globally unique, which is no good if you want seperate function objects with their own unique state. Here’s an example functor class:
With this class, I can create an instance that acts as a function, and each time you call it, it remembers the previous value of n, e.g.
You can’t do that with normal functions. But you can do it with lambdas: