Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursive lambda implemention in c++11

Tags:

c++

c++11

lambda

I interested to recursive lambda implementation, and found this code for Fibonacci calculation:

 std::function<int(int)> lfib = [&lfib](int n) {return n < 2 ? 1 : lfib(n-1) + lfib(n-2);};

And I have a question: std::function is a polymorphic function, so lfib creates/and saves the lambda in heap memory, not on the stack. And therefore may lose optimization possibilities of the program. Correct or not?

like image 734
Khurshid Normuradov Avatar asked Jul 24 '13 12:07

Khurshid Normuradov


People also ask

What is lambda expression in C++11?

C++11 introduces lambdas allow you to write an inline, anonymous functor to replace the struct f . For small simple examples this can be cleaner to read (it keeps everything in one place) and potentially simpler to maintain, for example in the simplest form: void func3(std::vector<int>& v) { std::for_each(v.

How do you write a recursive lambda function?

A recursive lambda expression is the process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily.

Can a lambda function be recursive?

This is an example of a function that will recursively call itself. Warning It's possible to run into infinite loops with recursive calls. Test your functions locally before deploying to production.

Can a lambda closure be used to create a C++11 thread?

Can you create a C++11 thread with a lambda closure that takes a bunch of arguments? Yes – just like the previous case, you can pass the arguments needed by the lambda closure to the thread constructor.


1 Answers

The type-erasure data which is the state of std::function will persist as long as the std::function or its copies live, probably via heap allocation.

The same is not true of the closure, which contains captured variables. That's part of the state of the lambda object, and probably contains the address of a data structure on the stack, which will disappear when the current function returns and the variable lfib goes out of scope.

Remember that you've captured lfib by reference. Therefore any changes to lfib for the remainder of the function have to be visible to the lambda (including but not limited to the initialization). The only way the compiler can manage that in a general way is by storing the address of the local lfib. In your particular case, if lfib is not assigned again, it might be possible for the compiler to store the value immediately post-initialization instead of a reference. But it's not guaranteed, and not even particularly likely.

like image 101
Ben Voigt Avatar answered Sep 29 '22 14:09

Ben Voigt