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?
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.
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.
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With