Lesson 2 of 7
Lambda Expressions - Captures, Generics & STL Integration
A **lambda** is a locally-defined anonymous function object (a closure). It captures variables from the surrounding scope, has its own `operator()`, and can be stored in `std::function<>` or passed directly to algorithms. Lambdas replaced verbose functor classes in modern C++. **Generic lambdas** (C++14) use `auto` parameters to create template-like lambdas. **Mutable lambdas** can modify captured variables.
Lambda Captures, mutable, Generic Lambdas & Immediate Invocation
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>
#include <string>
int main() {
int base = 10;
// ── Capture modes ─────────────────────────────────────────
auto capture_by_val = [base](int x){ return x + base; }; // copies base
auto capture_by_ref = [&base](int x){ return x + base; }; // ref to base
auto capture_all_val = [=](int x){ return x + base; }; // all by value
auto capture_all_ref = [&](int x){ return x + base; }; // all by ref
auto capture_mixed = [base, &base](int x){ return x; }; // not valid!
// Actually: [=, &specific] or [&, specific_by_val] are fine
auto mixed_ok = [=, &base](int x){ base++; return x + base; }; // ref override
base = 20;
std::cout << capture_by_val(5) << "
"; // 15 (captured old value: 10)
std::cout << capture_by_ref(5) << "
"; // 25 (sees new base: 20)
// ── mutable lambda - can modify by-value captures ─────────
int count = 0;
auto counter = [count]() mutable { // count is a copy, mutable lets us write
return ++count; // modifies local copy, not outer count
};
std::cout << counter() << "
"; // 1
std::cout << counter() << "
"; // 2
std::cout << count << "
"; // still 0 - outer unchanged
// ── Generic lambda (C++14) - auto parameters ──────────────
auto add = [](auto a, auto b) { return a + b; }; // works for any type
std::cout << add(3, 4) << "
"; // 7
std::cout << add(2.5, 1.5) << "
"; // 4.0
std::cout << add(std::string{"hi"}, std::string{"!"}) << "
"; // hi!
// ── Storing lambdas in std::function ─────────────────────
std::function<int(int)> fn = [base](int x){ return x + base; };
std::cout << fn(3) << "
"; // 23
// std::function has overhead (type erasure via virtual dispatch)
// For performance-critical code, use auto to keep lambda type
// ── Lambdas with STL algorithms ───────────────────────────
std::vector<int> nums{5, 2, 8, 1, 9, 3};
std::sort(nums.begin(), nums.end(),
[](int a, int b){ return a < b; }); // ascending
auto sq_sum = std::accumulate(nums.begin(), nums.end(), 0,
[](int acc, int n){ return acc + n*n; });
std::cout << "sq_sum=" << sq_sum << "
"; // 1+4+9+25+64+81=184
// ── Immediately Invoked Lambda ────────────────────────────
const int computed = []{
int result = 0;
for (int i = 1; i <= 10; ++i) result += i;
return result;
}(); // () - immediately invoked
std::cout << "1..10 sum=" << computed << "
"; // 55
// ── Lambda returning a lambda ─────────────────────────────
auto make_multiplier = [](int factor) {
return [factor](int x){ return x * factor; };
};
auto triple = make_multiplier(3);
auto double_it = make_multiplier(2);
std::cout << triple(5) << " " << double_it(5) << "
"; // 15 10
// ── Recursive lambda (C++14 with generic) ─────────────────
std::function<int(int)> fib = [&fib](int n) -> int {
return n <= 1 ? n : fib(n-1) + fib(n-2);
};
std::cout << "fib(10)=" << fib(10) << "
"; // 55
return 0;
}Common Mistakes
- Capturing by reference when the lambda outlives the scope - `auto fn = [&x]{ return x; }` - if `fn` is stored (e.g., in a callback) and called after `x` goes out of scope, it accesses a dangling reference. Capture by value (`[x]`) when the lambda might outlive its enclosing scope.
- `[=]` captures `this` by value in member lambdas in C++14 (the pointer `this`, not the object) - in C++14, `[=]` inside a member function captures `this` (so you can modify the object's members). In C++17, use `[*this]` to capture the object by value. This is a common source of dangling pointer bugs in asynchronous code.
- `std::function` overhead - `std::function<>` wraps any callable via type erasure (usually a virtual function call). For performance-critical callbacks called millions of times, use template parameters with lambda type directly: `template<typename F> void hof(F fn)` - zero overhead.
Tip
Tip
Practice Lambda Expressions Captures Generics STL Integration in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Capture syntax, generic lambdas, and conversion to function pointers
Practice Task
Note
Practice Task - (1) Write a working example of Lambda Expressions Captures Generics STL Integration from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Lambda Expressions Captures Generics STL Integration is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- A **lambda** is a locally-defined anonymous function object (a closure).
- Capturing by reference when the lambda outlives the scope - `auto fn = [&x]{ return x; }` - if `fn` is stored (e.g., in a callback) and called after `x` goes out of scope, it accesses a dangling reference. Capture by value (`[x]`) when the lambda might outlive its enclosing scope.
- `[=]` captures `this` by value in member lambdas in C++14 (the pointer `this`, not the object) - in C++14, `[=]` inside a member function captures `this` (so you can modify the object's members). In C++17, use `[*this]` to capture the object by value. This is a common source of dangling pointer bugs in asynchronous code.
- `std::function` overhead - `std::function<>` wraps any callable via type erasure (usually a virtual function call). For performance-critical callbacks called millions of times, use template parameters with lambda type directly: `template<typename F> void hof(F fn)` - zero overhead.
Finished this lesson?