C++ Closures

Lambda expressions in C++ are anonymous functions defined at moment of invokation. Syntatical details can be found elsewhere but a simple lambda expression is composed of an introducer, declarator and body. It would look like:

[](int a){ return a > 0; }

A Lambda can be invoked immediately with the function-call operator and can also be stored in function pointers or function wrappers.

Where these lambda expressions become closures is when they “store” their environments i.e. they capture variables at the scope where the lambda was created.

  • … no variables captured/accessed
  • [=] … variables captured by value
  • [&] … variables captured by reference

It is worth noting that capturing by reference comes with risk in that the closure can be invoked after the captured variable may no longer exist.

Anonymous functions can make debugging a little harder.

 Date: September 6, 2018
 Tags:  notes cpp

Previous
⏪ Windows Tips

Next
Shin Megami Tensei Generalizations ⏩