Lambda Expressions
Prerequisites: The Rule of Three, Five, and Zero
A lambda is an anonymous, inline function — used constantly alongside STL algorithms, exactly as seen already in STL Algorithms above.
auto add = [](int a, int b) { return a + b; };
std::cout << add(2, 3) << std::endl; // 5
int threshold = 5;
auto isAboveThreshold = [threshold](int n) { return n > threshold; };
// [threshold] "captures" the outer variable by value
[] (the capture list) controls what from the surrounding
scope the lambda can see: [threshold] captures by value (a
snapshot at creation time), [&threshold] by reference (sees
later changes), and [&]/[=] capture everything used, by
reference or by value respectively.
Common mistakes
- Capturing by reference (
[&]) and using the lambda after the referenced variable has gone out of scope — this is a dangling reference, exactly like returning a pointer to a local variable in C.