Modern C++ › C++11
Lambda Expressions
Captures, closures and using lambdas with algorithms.
Explanation
A lambda expression creates an unnamed function object (a closure) in place:
[captures](parameters) -> return_type { body }
The compiler writes a class with operator() for you: the lambda from Function Objects, without the boilerplate. The return type is usually deduced.
Captures decide which outer variables the body can use:
| Capture | Meaning |
|---|---|
[] |
nothing |
[x] / [&x] |
x by copy / by reference |
[=] / [&] |
everything used, by copy / by reference |
[=, &y] |
default copy, but y by reference |
[this] |
the enclosing object’s this pointer |
By-copy captures are const inside the lambda unless it is declared mutable. Each lambda has a unique, unnameable type; store one in auto or a std::function<Signature> (type-erased, slightly slower). A capture-less lambda converts to a plain function pointer.
Example
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{5, 3, 8, 1, 9, 2};
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; }); // descending
int limit = 4;
auto bigger = std::count_if(v.begin(), v.end(), [limit](int x) { return x > limit; });
std::cout << "bigger than " << limit << ": " << bigger << "\n"; // 3
int total = 0;
std::for_each(v.begin(), v.end(), [&total](int x) { total += x; }); // by reference
std::cout << "total " << total << "\n"; // 28
int counter = 0;
auto next = [counter]() mutable { return ++counter; }; // own copy
std::cout << next() << next() << " " << counter << "\n"; // 12 0
std::function<int(int)> fact = [&fact](int n) { return n <= 1 ? 1 : n * fact(n - 1); };
std::cout << fact(5) << "\n"; // 120
auto adder = [](int a) { return [a](int b) { return a + b; }; }; // returns a lambda
std::cout << adder(3)(4) << "\n"; // 7
return 0;
}
Common pitfalls
- Dangling reference captures: a lambda that captures locals by
&and outlives them (returned, stored, or run on another thread) reads freed stack memory. [=]capturesthisimplicitly (deprecated in C++20); with member data you copy the pointer, not the members.- By-copy captures are frozen at lambda-creation time, so later changes to the variable aren’t seen.
- Copying a large object into a capture is easy to do by accident with
[=]; list captures explicitly. - A lambda cannot refer to itself by name; use
std::function(as above) or a Y-combinator style trick.
Legacy vs modern
// C++98: named functor + std::bind2nd
struct GreaterThan { int n; bool operator()(int x) const { return x > n; } };
std::count_if(v.begin(), v.end(), GreaterThan{4});
// C++11
std::count_if(v.begin(), v.end(), [](int x) { return x > 4; });
C++14 adds generic lambdas and init-captures; C++17 adds constexpr lambdas and *this capture; C++20 adds template lambdas.
Exercises
1. Write a lambda that returns whether a std::string is longer than a minLen variable.
[minLen](const std::string& s) { return s.size() > minLen; }
2. What does mutable change?
It makes the lambda’s by-copy captures modifiable inside its body (the changes stay in the closure and don’t affect the originals).