Module 9 · Modern C++ — topic 1 of 3
Lambda Expressions
Lambdas are unnamed function objects written inline. Learn the syntax, captures by value and reference, mutable lambdas, generic lambdas and std::function.
Learning objectives
- Write lambdas with and without captures
- Choose between capture by value and by reference
- Pass lambdas to algorithms and store them in std::function
Definition
A lambda expression creates an unnamed function object (closure) that can capture variables from the enclosing scope; its syntax is [captures](parameters) -> return_type { body }.Introduction
Algorithms like sort and count_if need a small piece of behaviour — a comparison or a condition. Before C++11 you wrote a separate function or functor class; now you write the logic right where it's used.
Why it matters
Lambdas make STL algorithms concise and readable.
Callbacks, event handlers and threads all take lambdas.
Detailed explanation
[] captures nothing; [x] copies x; [&x] refers to x; [=] copies everything used; [&] references everything used; [this] captures the current object.
Captured copies are const inside the lambda unless it is declared mutable.
A reference capture must not outlive the variable — returning a lambda that captured a local by reference creates a dangling reference.
Generic lambdas (C++14) use auto parameters: [](auto a, auto b) { return a < b; }.
Each lambda has a unique type; store one with auto or, when the type must be uniform (e.g. a vector of callbacks), in std::function<R(Args...)> (with some overhead).
Syntax
- The return type is usually deduced.
- Prefer explicit captures over [=] and [&] in long-lived lambdas.
- Include
<functional>for std::function.
Code examples
Lambdas with algorithms
-2 3 5 -7 9 | above 4: 2
Value vs reference capture
10 20
The value capture copied x when the lambda was created.
More examples
mutable, generic lambdas and std::function
counter: 3 9 pear * -> 18 + -> 9 avg -> 4.5
Step-by-step explanation
[n = 0]creates a member n inside the closure;mutableallows changing it.- Each call increments the closure's own n: 1, 2, 3.
- The generic lambda works for ints and strings.
std::functionstores different lambdas with the same signature in one map (sorted by key: "*", "+", "avg").
Expected output
Running “mutable, generic lambdas and std::function” prints exactly:
Practical applications
- GUI frameworks connect button clicks to lambdas.
- Thread pools take lambdas as tasks.
- Sorting UIs by different columns uses lambda comparators.
Best practices
- Keep lambdas short; name complex ones.
- Capture explicitly what you use.
- Prefer auto over std::function when you don't need type erasure.
Common mistakes
Dangling reference capture
Avoid
Prefer
The local is destroyed when make returns; capture by value instead.
Modifying a value capture
Avoid
Prefer
Captured copies are const unless the lambda is mutable.
Important notes
- C++20 allows template parameter lists on lambdas:
[]<typename T>(T x) { ... }. - Lambdas with no captures convert to plain function pointers, usable with C APIs.
Key takeaways
- Lambdas are inline function objects with captures.
- Value captures copy; reference captures alias.
- std::function stores any callable with a given signature.
Try it yourself
- 1Sort a vector of strings by length, then alphabetically, using one lambda.
- 2Write a function returning a lambda that adds a captured number to its argument.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
6 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhat is printed?
- ModerateWhat is printed?