Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is meant by 'retain state' in c++?

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?

like image 503
kiriloff Avatar asked Jul 04 '12 06:07

kiriloff


1 Answers

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:

class Counter
{
    int n;
public:
    Counter() :n(0) {}
    int operator()() { return n++; }    
};

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.

Counter x;
cout << x() << '\n';
cout << x() << '\n';
cout << x() << '\n';

You can't do that with normal functions. But you can do it with lambdas:

int n = 0;
auto x = [=]() mutable { return n++; };
cout << x() << '\n';
cout << x() << '\n';
cout << x() << '\n';
like image 115
Benjamin Lindley Avatar answered Sep 30 '22 08:09

Benjamin Lindley