1) Why is not the lambda inside the function called, please?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
void test() {
int n=0;
[&]() { std::cout << "Inside the lambda!\n"; ++n; };
std::cout << n <<"\n"; // n = 1
}
int main() {
test();
system("pause");
return 0;
}
2) When is a lambda called, actually?
3) Should I declare it this way: [&]() { std::cout << "Inside the lambda!\n"; return; } (); to be called?
4) If that way called, the local variable captured, n, can be mutated, but I've heard that captured objects by the lambda are const by default.
1. A lambda is simply a value. Line 5 is analogous to doing something like
1 2
int n = 0;
"something";
It's a statement that contains a value but doesn't do anything with it.
2. When it's operator()() is called.
3. Yes, that would cause the lambda to be called immediately. You could also assign it to an object and call that object, or pass the lambda to a function that may or may not call it.
1 2
auto f = [&]() { std::cout << "Inside the lambda!\n"; ++n; };
f();
4. Only when said objects are captured by value. If you capture by reference, the reference is non-const (unless the captured object is const, obviously), since it's quite reasonable that if someone is capturing by reference that they'll want to modify the actual object.
auto f = [&]() { std::cout << "Inside the lambda!\n"; ++n; };
f(); // <-- here
[&]() {
std::cout << "Inside the lambda!\n";
++n;
} (); // <-- here
¿do you understand pass by value and pass by reference in function arguments? it's the same idea.
if you want your lambda to modify the captured variables, capture them by reference
if you don't want to modify them, capture by value
1 2 3
in n = 42;
[n](){ n = 54; } // compile error
[&n](){ n = 54; } // fine
lambdas aren’t functions (which is part of how they avoid the limitation of C++ not supporting nested functions). They’re a special kind of object called a functor. Functors are objects that contain an overloaded operator() that make them callable like a function.
@ frek, a book on lambdas I found useful is Bartłomiej Filipek's "C++ Lambda Story". It shows the history of lambdas from C++98 to C++20. Available on Amazon in paperback or as an eBook in several formats at leanpub.
The leanpub version is what I own and I found it very useful to "get under the hood" of why we have lambdas and how they work.