Modern (Effective) C++ - What are lambdas, closure, closure classes.

Lambdas add a lot of power to C++, even though there is nothing new that it achieves, which was earlier not achievable by regular functions / functors.

But lambdas are much easier and expressive than function objects. They are most commonly used in
  • Specifying predicates for STL algorithms like std::copy_if, std::sort etc.
  • Used to create deleter functions for smart pointers.

When it comes to lambdas, there are three terms to understand, even though they are often used interchangeably.
  1. Lambda expression is the code itself.
  2. Closure is the runtime object created from the lambda. Closure hold copies or references to captured variables.
  3. Closure class is the class from the which the closure is instantiated. Each lambda causes a unique class to be generated, with the code in lambda, as it's  member function. In the below program, we can see the names of the generated classes.




Modern (Effective) C++ - What are lambdas, closure, closure classes. Modern (Effective) C++ - What are lambdas, closure, closure classes. Reviewed by zeroingTheDot on March 10, 2018 Rating: 5

No comments:

Powered by Blogger.