Effective Modern C ++ lambda expressions of

lambda expressions in C ++ 11 is to add features. lambda expression (expression callable: functions, function pointers, lambda expressions, std :: bind, function object class) is a callable expression. lambda expression can generally be used in the creation and deletion as a family of algorithms for the smart pointer argument passed, and so on.

lambda expressions can create closures (runtime objects created lambda expressions), the closure also can be replicated.

    auto lambda_1 = [](int a, int b) {return a + b; };
    auto lambda_2 = lambda_1;

Default capture mode in C ++ lambda expressions in two ways: by value and by reference capture capture. Capture only non-static local variable for the lambda expression to create scope visible lambda expression.

        int a = 1;
	int b = 2;
	auto _lambda = [=a]() {return a; };
	auto _lambda_ = [&b]() {return b; };

By reference capture could result in vacant cited as a reference or pointer returned by the function if a non-static local variable, and lambda expressions just caught it, then it will lead to dangling reference. Another case is if we capture the life cycle of non-static local variables created more than l lifecycle ambda expression should be short, can lead to dangling reference. The same also applies to non-static local variable by copying capture.

Description captured by value capture is a copy of the non-static local variable, that is to say the non-static local variables between a copy and are independent. If the non-static local variable is a pointer, it may cause a copy of the vacant, that is to delete a pointer, for a visit.

; Lambda expression can capture not only non-static local variable and parameter lambda expressions, and while you can also rely on (not capture oh) static storage variables.

There, C ++ may be used in auto 14 in the lambda expression parameter.

auto lambda_3 = [](auto _a, auto _b) {return _a + _b; };

In C ++ 14 also introduces a wide range of lambda expressions (also called initialization expression). A wide range of lambda expressions (on the surface) capture the behavior does not exist.

	auto lambda_4 = [a = a]() {return a; }; //实质是在lambda创建的闭包里面创建一个对象,然后复制到闭包里的该对象中。
	auto lambda_5 = [a=(std::move(a))]{ return a; }; //  //实质是在lambda创建的闭包里面创建一个对象,然后移动到闭包里的该对象中。

The above code is to initialize capture non-static local variable. "=" On the left, it is that you create to specify the name of the member variables in a closure. "=" On the right side, is the initialization expression.

We've had, is also a function object class callable expressions. And (class member function contains operator ()) is the essence of a lambda expression is a function object class

发布了77 篇原创文章 · 获赞 11 · 访问量 5068

Guess you like

Origin blog.csdn.net/qq_43145594/article/details/104310338