General features: lambda expressions

code

Syntax

 

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; }

Uses

  • 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

PROS

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

CONS

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

Capturing entire enclosing scope by value can be very expensive!

Pitfalls

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.

Leave a comment

Your email address will not be published.