Lambda Introduction
Introduced in C++11, lambda expressions allow for defining anonymous functions inline. They capture variables from their surrounding scope to create compact and powerful function objects, often used with STL algorithms.
Basic Syntax
A lambda is defined using '[]', '()', and '{}'. The '[]' captures variables, '()' lists parameters, and '{}' contains the code. Example: auto func = [](int x) { return x * x; };
Capture Clauses
Captures can be by value, by reference, or a mix. '[=]' captures all variables by value, '[&]' by reference. '[x, &y]' captures 'x' by value and 'y' by reference. Use captures minimally for efficiency.
Default Capture Modes
C++14 introduced default captures, allowing 'x' to be captured by value and others by reference using '[x, &]'. Conversely, capture 'x' by reference and others by value with '[=, &x]'.
Mutable Lambdas
By default, value-captured variables cannot be modified. Using 'mutable' allows changes: auto c = [x]() mutable { x++; return x; }; Mutable lambdas cannot be constexpr.
Generic Lambdas
C++14 introduced generic lambdas, using 'auto' in the parameter list. They allow the function to accept any type: auto generic = [](auto x) { return x + x; };
Lambda to Function Pointer
Lambdas with empty capture lists can be converted to function pointers. Useful for C APIs compatibility: void (*funcPtr)(int) = [](int x) { std::cout << x; };