Lambdas are one of the most important features introduced in C++11, transforming C++ into a modern, expressive, multi-paradigm language.
What Is a Lambda?
A lambda is:
An anonymous function object (anonymous functor).
It is syntactic sugar for a class with operator().
Compiler transformation (conceptually):
auto add = [](int a, int b){ return a + b; };
Becomes something like:
class __Lambda {
public:
int operator()(int a, int b) const {
return a + b;
}
};
__Lambda add;
Lambda Syntax Breakdown
[capture](parameters) -> return_type {
body
};
Example:
auto multiply = [](int x, int y) -> int {
return x * y;
};
Most of the time, return type is deduced:
auto multiply = [](int x, int y) {
return x * y;
};
The Capture List
The capture list allows lambdas to access external variables.
[ ] → capture nothing
[=] → capture everything by value
[&] → capture everything by reference
[x] → capture x by value
[&x] → capture x by reference
Example:
int factor = 5;
auto scale = [factor](int x) {
return x * factor;
};
By Value
int x = 10;
auto f = [x]() {
return x + 5;
};
x = 20;
std::cout << f(); // 15
Captured copy does not change.
By Reference
int x = 10;
auto f = [&x]() {
return x + 5;
};
x = 20;
std::cout << f(); // 25
Mutable Lambdas
By default, lambdas are const.
To modify captured-by-value variables:
int x = 10;
auto f = [x]() mutable {
x += 5;
return x;
};
mutable removes const from operator().
Generic Lambdas (C++14)
Templates without writing templates.
auto add = [](auto a, auto b) {
return a + b;
};
Works for:
int
double
std::string
custom types with operator+
Lambdas and STL
Modern STL heavily relies on lambdas.
Example:
#include <algorithm>
#include <vector>
std::vector<int> v = {1, 2, 3, 4};
std::sort(v.begin(), v.end(), [](int a, int b) {
return a > b;
});
Before C++11, you'd need a functor class.
When to Use Lambdas
Use lambdas when:
✔ Short inline logic
✔ STL algorithm customization
✔ Local transformation logic
✔ Higher-order function usage
✔ Avoiding unnecessary class definitions
Avoid lambdas when:
✖ Large complex logic
✖ Reusable public API components
✖ When named type improves clarity