std::find_if(container.begin(),container.end(), [](int val) {return 0 < val && val < 10;} );
中的
[](int val) {return 0 < val && val < 10;}
lambda创建的运行时对象,这个对象是一个闭包 (closure)。例如在上面代码std::find_if中这个closure是一个对象被作为第三个参数传递到std::find_if里。
一个闭包类(closure class),实例化一个闭包。每个lambda都会引起编辑器生成一个闭包类,lambda里面的语句成为闭包类成员函数的执行语句。
int x; //x is local variable
auto c1 = [x](int y) {return x * y > 55;}; //c1 is copy of the closure produeced by the lambda
auto c2 = c1; //c2 is copy of c1
auto c3 = c2;
c1,c2,c3都是lambda创建的闭包的副本。
two default capture modes in c++ 11:by-reference and by-value.
using FilterContainer = std::vector<std::function<bool(int)> >;
FilterContainer filters;
class Widget
{
public:
void addFilter()const
{
filters.emplace_back([=](int value) {return value % divisor == 0; });
}
private:
int divisor;
};
filters.emplace_back([](int value) {return value % divisor == 0; });
上面这个语句是编译不过的,因为在addFilter函数里没有divisor这个变量,这个变量是属于类Widget的。
filters.emplace_back([=](int value) {return value % divisor == 0; });
编译过是以为他传递的this,相当于:
void Widget::addFilter()const{
auto currentObjectPtr = this;
filter.emplace_back(
[currentObjectPtr](int value)
{
return value%currentObjectPtr->divisor == 0;
}
);
}
原文:https://www.cnblogs.com/ultramanX/p/14785926.html