Functions
Lambda Expressions
Anonymous functions in C++11+
Interview: Modern C++ feature
Lambda Expressions
Lambdas (C++11) are anonymous, inline function objects. They capture surrounding variables from the enclosing scope, enabling powerful functional programming patterns. Internally, the compiler transforms each lambda into a unique unnamed class with an overloaded operator().
Capture Clause
| Capture | Meaning |
|---|---|
| [] | No captures |
| [=] | Capture all by value (copy) |
| [&] | Capture all by reference |
| [x, &y] | x by value, y by reference |
| [this] | Capture this pointer (class members) |
Generic Lambdas (C++14)
Using auto parameters in lambdas creates generic (templated) lambdas that work with any type: auto add = [](auto a, auto b) { return a + b; };
Interview Corner
Q: What is the danger of capturing by reference in a lambda that outlives its scope?
A: If a lambda captures a local variable by reference and then outlives the local scope (e.g., stored in a callback, passed to another thread, or stored in a container), the reference becomes a dangling reference — accessing destroyed memory. This is undefined behavior. Prefer capturing by value [=] for lambdas that may outlive the enclosing scope.
Q: What is the difference between std::function and auto for storing lambdas?
A: auto stores the exact lambda type with zero overhead. std::function uses type erasure and dynamic dispatch, adding overhead (heap allocation for captures, virtual call). Use auto for local lambdas and std::function only when you need runtime polymorphism (storing different callables in a container).
Common Pitfalls
- Dangling reference captures: Capturing local variables by reference in lambdas that outlive the local scope.
- Capturing this in long-lived callbacks: If the object is destroyed before the lambda executes,
thisbecomes dangling. Capture ashared_ptrto the object instead.
Best Practices
- Prefer explicit captures [x, y] over blanket [=] or [&] for clarity and safety.
- Use lambdas with STL algorithms (
std::sort,std::transform,std::find_if) for clean, expressive code.