Lambdas in C++

From the C++ cheat sheet · Lambdas & std::function · verified Jul 2026

Lambdas

Inline callables with captures.

cpp
// Quick Reference
auto add = [](int a, int b) { return a + b; };
int factor = 3;
auto mul = [factor](int x) { return x * factor; };  // capture by value
auto ref = [&sum](int x) { sum += x; };             // capture by reference
💡 [=] captures everything by copy, [&] by reference; name specific vars to be explicit.
⚡ Capturing by reference into a lambda that outlives the variable dangles - prefer by value there.
📌 Add mutable to let a lambda modify its by-value captures between calls.
🟢 std::function stores any callable but adds overhead - use auto for local lambdas.
lambdasfunctional
Back to the full C++ cheat sheet