Modern C++ • C++20 baseline
Lambdas, Captures, and Callable Objects
Create small function objects while making captured state and its lifetime clear.
A lambda has a unique closure type and can capture values or references from its surrounding scope. Capturing by value stores a copy; capturing by reference requires the referenced object to outlive every call. Generic lambdas use auto parameters and are templates under the hood.
Key points
- Prefer explicit captures in code that is stored or called later.
- A lambda returned from a function must not capture local variables by reference.
Example
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
const int minimum = 5;
const std::vector<int> values{2, 8, 4, 9};
const auto found = std::find_if(values.begin(), values.end(),
[minimum](int value) {
return value >= minimum;
});
if (found != values.end()) {
std::cout << *found << '\n';
}
}
What to expect
8
Practice exercise
Change the predicate to capture a configurable minimum by value. Then consider whether a reference capture would be safe if the predicate were stored.
Key idea: Capture choices are ownership and lifetime choices; make them deliberate.