Difficulty: Advanced
What is a lambda expression in C++? Explain capture by value vs by reference, the mutable keyword, init-captures, and the dangling reference risk.
Lambdas are a small feature with a huge effect on how STL code looks, so expect to see one in nearly every modern C++ coding round. The syntax is compact, but there are several rules worth knowing precisely.
A lambda is an inline, unnamed function object. Writing '[capture](params) { body }' makes the compiler generate a unique class with an operator() containing your body, and data members for whatever you captured. So a lambda is just a struct with a call operator, which is why it can be inlined so well when passed to std::sort or std::find_if. Its type is unique and unspeakable, so you store it with auto, or in a std::function if you need type erasure (with an allocation and an indirect call as the price).
The capture list decides which outside variables the body can use. [x] copies x into the lambda at the moment of creation. [&x] stores a reference to x. [=] captures everything used by copy, and [&] captures everything used by reference. Prefer explicit captures over blanket ones; they document intent and avoid surprises. A vital detail: [=] inside a member function captures the this pointer, not a copy of the members, so the lambda still depends on the object staying alive (C++20 deprecates the implicit [=] capture of this).
Copies are constant by default: the call operator is const, so you cannot modify a by-value capture unless you mark the lambda mutable. Even then you are only changing the lambda's own copy, and it persists across calls of the same lambda object. It's like taking a photocopy of a form: scribbling on your copy never changes the original, but it keeps your scribbles the next time you look at it.
C++14 added init-captures (generalised captures): [n = 0] creates a member initialised with any expression, and [p = std::move(ptr)] moves a move-only object like a unique_ptr into the lambda, something plain capture cannot do. C++14 also brought generic lambdas with auto parameters, and C++20 added template parameters and allowed lambdas in unevaluated contexts.
The risk everyone must know: capturing by reference and then letting the lambda outlive the variable. If you return a lambda that has [&] over a local, or hand it to a thread or store it for a callback, calling it later reads a dangling reference and is undefined behaviour. When a lambda escapes its scope, capture by value (or move). Also note that by-value capture takes a snapshot at creation, so later changes to the original are not seen, while a reference capture always sees the current value.
Finally, mention constexpr lambdas (implicit in C++17 when eligible), the fact that captureless lambdas convert to plain function pointers, and recursion tricks (a generic lambda taking itself as a parameter, or std::function).
#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
int main() {
int x = 10;
auto byVal = [x] { return x; };
auto byRef = [&x] { return x; };
x = 20;
std::cout << byVal() << " " << byRef() << "\n"; // 10 20
auto counter = [n = 0]() mutable { return ++n; }; // init-capture + mutable
std::cout << counter() << counter() << counter() << "\n"; // 123
auto p = std::make_unique<int>(42);
auto owner = [q = std::move(p)] { return *q; }; // move-only capture
std::cout << owner() << " " << (p == nullptr) << "\n";
std::vector<int> v{5, 2, 8, 1};
int threshold = 3;
auto n = std::count_if(v.begin(), v.end(), [threshold](int a) { return a > threshold; });
std::cout << n << "\n";
}
by-value capture is a snapshot; by-reference sees later changes. The mutable counter keeps its own state between calls. The unique_ptr is moved into the lambda so p becomes null.
lambda, capture by value, capture by reference, mutable, init capture