Lambdas
They are inline functions which can be used for short snippets of code that are not going to be reused and therefore do not require a name.
Syntax
Parameters and return type
Return type is usually inferred.
But required if:
Multiple return paths
Confusing types
Usage
Capture List
The capture list decides what outside variables the lambda can see and how.
1. Capture nothing
2. Capture by value
The value of a is replaced at the definition of the lambda expression, hence it does not access the latest/updated value of a, but the original copied value of a.
Moreover, Here we cannot modify the value of captured variables inside the lambda expression.
Capture by value variables are read-only.
3. Capture by reference
Refers to the original variable
4. Capture everything
5. Mixed capture
Lambdas vs function pointers
Lambdas without captures ✅ can be converted to function pointers.
Internal Implementation
A lambda is an unnamed function object.
It creates:
A compiler-generated class
With an overloaded
operator()