Skip to content

Lambda Expressions

Map of STL Algorithms

Lambda Expressions

Map of STL Algorithms

The World Map of C++ STL Algorithms

world map C++ STL algorithms

List of algorithms

Lambda

Lambda expression creates anonymous function object

1
[capture-list] (parameter-list) {statement-list}

Minimal lambda: [] {}

With return type:

1
[capture-list] (parameter-list) -> return-type {statement-list}

Lambdas without capture (stateless) are compatible with plain C functions

1
2
3
4
5
auto lambda = [](int i) -> int { return 42*i; } // precise type

using func_t = int(*)(int);         // type of function-pointer
typedef int (*func_t)(int);         // C version using typedef
func_t p_lambda = lambda;           // type decay from lambda to function pointer
  • Default capture by reference may lead to dangling references to destroyed scope.
  • Default capture by values may lead to dangling pointers to destroyed scope (through this).
  • Default capture by values does not capture static variables, but uses them by reference instead.
  • Default capture is safe when used locally, but even then someone may copy-paste them into unsafe environment
  • \Rightarrow explicit capture forces to think, hence safer

Lambda Init

  • Capture ownership (unique_ptr, future, thread)
  • [ var = initExpr ] (...) {...}
  • Left of = is inner scope, right of = is outer scope
1
2
3
4
5
6
7
class Widget {
 bool isValidated() const;
 bool isArchived() const;
};
auto pw     = std::make_unique<Widget>();
auto test = [pw = std::move(pw)] // reuse the "pw" name
 { return pw->isValidated() && pw->isArchived(); }

Last update: June 15, 2021