C++ Lambda

| 分类 C++  | 标签 Effective_Modern_C++ 

The vocabulary associated with lambdas can be confusing. Here’s a brief refresher:

  • A lambda expression is just that: an expression. It’s part of the source code. Like {return lhs >= rhs?lhs:rhs;}.
  • A closure is the runtime object created by a lambda.
  • A closure class is a class from which a closure is instantiated. Each lambda causes compilers to generate a unique closure class. The statements inside a lambda become executable instructions in the member functions of its closure class.

Item 31: Avoid 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. Default by-value capture lures you into thinking you’re immune to that problem (you’re not), and it lulls you into thinking your closures are self-contained (they may not be).

A by-reference capture causes a closure to contain a reference to a local variable or to a parameter that’s available in the scope where the lambda is defined. If the lifetime of a closure created from that lambda exceeds the lifetime of the local variable or parameter, the reference in the closure will dangle.

For by-value capture, the problem is that if you capture a pointer by value, you copy the pointer into the closures arising from the lambda, but you don’t prevent code outside the lambda from deleteing the pointer and causing your copies to dangle.


上一篇     下一篇