General features: lambda expressions



Note: the code from above is no longer necessary in C++14, the compiler will deduce the return type.


Usage / Usability

Capture list

  • [] take none of the variables from the enclosing scope
  • [&] take all the variables from the enclosing scope by reference
  • [=] take all the variables from the enclosing scope by value

There is also support for capture-by-name, to capture only part of the enclosing scope.

Return type

  • suffix return style: [] (int a, int b) -> bool { return a < b; }


  • Great with STL algos
  • predicates for *_if algo
  • algos using comparison functions (sort etc)
  • quick custom deleters for unique_/shared_ ptr
  • on the fly callback functions


  • Does not pollute namespace
  • Great for one- or two-liners


  • Less readable – intent may not be clear
  • Can easily create obfuscated code!

Capturing entire enclosing scope by value can be very expensive!


Danger of dangling pointers due to default capture modes

  • There are two default capture modes in C++11: by-reference and by-value
  • Default by-reference capture can lead to dangling references.

If the lambda exceeds the lifetime of the local object it captures, the reference from the lambda will dangle.

Quiz – What line shall we use for the following function?

Answer: 3rd line. the other one capture by reference, and add into the global vector, and by the time we will call the lambdas, the captured reference (divisor) will be a dangling reference.

You may also like...

Leave a Reply