lambda以及易错点分析

1 理解lambda

  1. lambda就是一个仿函数的实例化,是为了解决书写模板的复杂度
  2. lambda如果只用auto,则是auto型参数推导,只是值传递推导,如果有->则是占位,如果 lambda 体包含单个返回语句,编译器将从返回表达式的类型推导返回类型。 否则,编译器会将返回类型推导为 void
  3. 捕获器只能捕获有限生命周期的变量,如静态存储持续时间的变量如全局变量静态变量是不能捕获的!!!
  4. 一定要注意是值传递还是引用传递,如果是值传递,则注意前后的值变化

https://docs.microsoft.com/en-us/cpp/cpp/examples-of-lambda-expressions?redirectedfrom=MSDN&view=vs-2019详细lambda

在这里插入图片描述

2 Lambda 表达式的属性

在这里插入图片描述
[]是与外界交换的参数,()是lambda作为仿函数实际需要使用的参数,mutable是指如果[]里的参数是值传递,则只读,rettype是返回值类型

图中的标注如下所示:

  1. lambda-introducer(在本主题的后面称为“capture 子句”)

  2. lambda declarator(在本主题的后面称为“参数列表”)

  3. mutable(在本主题的后面称为“可变规范”)

  4. exception-specification(在本主题的后面称为“异常规范”)

  5. trailing-return-type(在本主题的后面称为“返回类型”)

  6. compound-statement(在本主题的后面称为“lambda 体”)

以下各节对该语法进行了更详细的说明。

2.1 Capture 子句

lambda 表达式是类、构造和函数调用运算符。 如同,在定义类时,决定需要发生的对象捕获变量不受值还是引用或者是否是必需的。 如果 lambda 表达式需要访问局部变量和函数参数,它们需要 捕获。 get 子句 (语法中的lambda-introducer ) 所指定 lambda 表达式的主体是可以访问在封闭范围内的变量通过值或通过引用:包含" &的变量 (&) 为前缀) 没有 & 前缀的引用和变量访问值由访问。

空 capture 子句 [ ] 指示 lambda 表达式的主体不访问封闭范围中的变量。

捕获默认模式指定您未显式指定的获取变量是否捕获通过值或通过引用,如果使用它们。 您可以通过将 & 或 = 指定为 capture 子句的第一个元素来指定默认捕获模式(语法中的 capture-default)。 & 元素指定 lambda 表达式的主体通过引用访问所有捕获的变量,除非您显式地另行指定。 = 元素指定 lambda 表达式的主体通过值访问所有捕获的变量,除非您显式地另行指定。 例如,如果 lambda 表达式的主体通过引用访问外部变量 total 并通过值访问外部变量 factor,那么以下 capture 子句等效:

[&total, factor]
{factor, &total]
[&, factor]
[factor, &]
[=, &total]
[&total, =]

有关使用 capture-default 的一种常见的误会位于范围内的任何变量捕获是否使用 lambda。 事实上并非如此 - 在 lambda 提到的那些变量捕获,则使用 capture-default。

如果捕获子句包括 capture-default&,该 lambda 的 get 子句 capture 的 identifier 不能由 &。 沿着同一行,因此,如果获取子句包括 capture-default (=),该子句获得每个 capture 必须以窗体 & identifier。 标识符或 this 不能多次出现在子句获得。 下面的代码段阐释了一些示例。

struct S { void f(int i); };

void S::f(int i) {
    [&, i]{};    // OK
    [&, &i]{};   // ERROR: i preceded by & when & is the default
    [=, this]{}; // ERROR: this when = is the default
    [i, i]{};    // ERROR: i repeated
}
template<class... Args>
void f(Args... args) {
    auto x = [args...] { return g(args...); };
    x();
}

可以将 lambda 表达式用于类方法的主体中。 将 this 指针传递到 capture 子句以提供对封闭类的方法和数据成员的访问权限。 有关示例演示如何使用类用方法的 lambda 表达式,请参见示例:使用将方法的 Lambda 表达式。主题 Lambda 表达式的示例。

在使用子句获得时,应记住这些,理解和压力,尤其当使用具有多线程时的 lambda:

引用获取可用于修改变量之外,获取值,而无法用于修改变量之外 (变量允许复制修改,从原始的)。

而值获取不会反映更新给变量,则获取引用会反映更新到变量中。

而值获取没有生存期依赖关系,这些依赖关系的引用,获取引入生存期依赖关系,这些依赖关系。

2.2 参数列表

参数列表 (lambda declarator) lambda 表达式中为选项并类似于函数的参数列表。

lambda 表达式可以将另一个 lambda 表达式作为其参数。 有关详细信息,请参阅主题 Lambda 表达式的示例中的“高阶 Lambda 表达式”。

lambda 表达式的参数列表可以是可选的。 可以省略空括号,如果不传递参数到 lambda 表达式,并且 lambda-declarator: 不包含 exception-specification、trailing-return-type、mutable。

2.3 可变规范

通常的 lambda 函数调用运算符为 Const 按值,但是,mutable 可以取消此操作。 它不导致变量的数据成员。 可变规范使用 lambda 表达式的主体修改由捕获值的变量。 某些示例本文后面演示了 mutable 关键字的用法。

2.4 异常规范

您可以使用 throw() 异常规范来指示 lambda 表达式不会引发任何异常。 与正则函数一样,如果 lambda 表达式声明 throw() 异常规范且 lambda 体引发异常,Visual C++ 编译器将生成警告 C4297,如以下示例所示:

// throw_lambda_expression.cpp
// compile with: /W4 /EHsc 
int main() // C4297 expected
{
   []() throw() { throw 5; }();
}

2.5 返回类型

lambda 表达式的返回类型自动推断,并且,这发生,而无需添加关键字,除非指定 trailing-return-type。auto trailing-return-type 类似于普通方法或函数返回类型的部件。 但是,遵循返回类型参数列表,您必须包括尾部的返回类型关键字 ->,在返回类型。

如果 lambda 体包含单个返回语句或 lambda 表达式不返回值,则可以省略 lambda 表达式的返回类型部分。 如果 lambda 体包含单个返回语句,编译器将从返回表达式的类型推导返回类型。 否则,编译器会将返回类型推导为 void(可能需要显示指明返回类型)。 考虑阐释此原则下面的示例代码段。

auto x1 = [](int i){ return i; }; // OK: return type is int
auto x2 = []{ return{ 1, 2 }; };  // ERROR: return type is void, deducing 
                                  // return type from braced-init-list not valid

lambda 表达式可以生成另一个 lambda 表达式作为其返回值

2.6 Lambda 体

lambda 表达式主体的 lambda (compound-statement) 中可以包含一般的方法或函数主体所能包含的所有内容。 普通函数和 lambda 表达式的主体均可访问以下变量类型:

  1. 参数

  2. 本地声明变量

  3. 类数据成员 (在声明类和 this 内捕获)

  4. 具有静态存储持续时间的任何变量(例如,全局变量)

此外,lambda 表达式可以访问它从封闭范围中捕获的变量。 如果某个变量显示在 lambda 表达式的 capture 子句中,则该变量是显式捕获的。 否则,该变量是隐式捕获的。 lambda 表达式的主体使用默认捕获模式来访问隐式捕获的变量。

以下示例包含通过值显式捕获变量 n 并通过引用隐式捕获变量 m 的 lambda 表达式:

// captures_lambda_expression.cpp
// compile with: /W4 /EHsc 
#include <iostream>
using namespace std;

int main()
{
   int m = 0;
   int n = 0;
   [&, n] (int a) mutable { m = ++n + a; }(4);
   cout << m << endl << n << endl;
}
5
0

由于变量 n 是通过值捕获的,因此在调用 lambda 表达式后,变量的值仍保持 0 不变。 指定 mutable 允许 n 是在 lambda 中修改。

尽管 lambda 表达式只能捕获具有自动存储持续时间的变量,但您可以在 lambda 表达式的主体中使用具有静态存储持续时间的变量。 以下示例使用 generate 函数和 lambda 表达式为 vector 对象中的每个元素赋值。 lambda 表达式将修改静态变量以生成下一个元素的值。

void fillVector(vector<int>& v)
{
    // A local static variable.
    static int nextValue = 1;

    // The lambda expression that appears in the following call to
    // the generate function modifies and uses the local static 
    // variable nextValue.
    generate(v.begin(), v.end(), [] { return nextValue++; }); 
    //WARNING: this is not thread-safe and is shown for illustration only
}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

3 lambda作为模板参数输入

  1. auto cmp = {}; cmp为仿函数实例,decltype(cmp)为仿函数的类型,注意的是auto并不是lambda的返回值类型,而是lambda的类型
  2. 注意 【】( ){ } 是可以作为实例传入函数当做参数的,因为【】(){}就是cmp
int a[4] = {11, 2, 33, 4};
sort(a, a+4, [=](int x, int y) -> bool { return x%10 < y%10; } );
for_each(a, a+4, [=](int x) { cout << x << " ";} );
template<class interator, class Function>
void forr_each(interator beg,interator end,Function f)  //for_each的实现方式
{
    while(beg!=end)
    f(*beg++);
}

int b[]={11,2,35,43,54};
sort(b,b+5,[](int x, int y){return x%10<y%10;});
for_each(b,b+5,[](int x){cout<<x<<endl;});
forr_each(b,b+5,[](int x){cout<<x<<endl;});

int id = 1;
auto ff = [=]()mutable{cout<<id<<endl;id++;};//mutable表示可修改捕获的值,如果传=表示隐传递值,&表示引用
ff();
ff();
  1. 注意=与&隐传递
    [=, &x, &y]表示外部变量 x、y 的值可以被修改,其余外部变量不能被修改;
    [&, x, y]表示除 x、y 以外的外部变量,值都可以被修改。
  2. 注意下图所示要取出lambda的类型,需要decltype
    在这里插入图片描述

易错点分析


#include<iostream>
#include<vector>
using namespace std;
static int a = 1;
template<class T>
decltype(auto) fun(T t){return t[1];};  //1

template<class T>
auto fun1(T t){return t[1];}; //2

template<class T>
auto fun2(T t)->decltype(t[1]){return t[1];};//3
int main()
{
vector<int> ve{1,2,3};
int i = 1;
auto f = [&i]()mutable{i++;cout<<i<<endl;return i;};
auto f = [a]()mutable{i++;cout<<i<<endl;return i;};//a是全局变量不能捕获
f();
fun(ve)=100;
fun1(ve)=100;//error,auto值传递推导成右值int
fun2(ve)=100;
return 0;
}

下面的代码示例使用从前面的函数,并将该表达式的 lambda 表达式的示例与 STL generate_n的算法。 该 lambda 表达式分配的 vector 对象的元素。前两个元素的和的。 改用 mutable 关键字,这样 lambda 表达式体才能改变其外部变量 x 和 y的复制,lambda 表达式按值捕获。 由于 lambda 表达式按值捕获原始变量 x 和 y,它们的值保持为 1,在 lambda 后执行。

// compile with: /W4 /EHsc
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>

using namespace std;

template <typename C> void print(const string& s, const C& c) {
    cout << s;

    for (const auto& e : c) {
        cout << e << " ";
    }

    cout << endl;
}

void fillVector(vector<int>& v)
{
    // A local static variable.
    static int nextValue = 1;

    // The lambda expression that appears in the following call to
    // the generate function modifies and uses the local static 
    // variable nextValue.
    generate(v.begin(), v.end(), [] { return nextValue++; });
    //WARNING: this is not thread-safe and is shown for illustration only
}

int main()
{
    // The number of elements in the vector.
    const int elementCount = 9;

    // Create a vector object with each element set to 1.
    vector<int> v(elementCount, 1);

    // These variables hold the previous two elements of the vector.
    int x = 1;
    int y = 1;

    // Sets each element in the vector to the sum of the 
    // previous two elements.
    generate_n(v.begin() + 2,
        elementCount - 2,
        [=]() mutable throw() -> int { // lambda is the 3rd parameter
        // Generate current value.
        int n = x + y;
        // Update previous two values.
        x = y;
        y = n;
        return n;
    });
    print("vector v after call to generate_n() with lambda: ", v);

    // Print the local variables x and y.
    // The values of x and y hold their initial values because 
    // they are captured by value.
    cout << "x: " << x << " y: " << y << endl;

    // Fill the vector with a sequence of numbers
    fillVector(v);
    print("vector v after 1st call to fillVector(): ", v);
    // Fill the vector with the next sequence of numbers
    fillVector(v);
    print("vector v after 2nd call to fillVector(): ", v);
}

猜你喜欢

转载自blog.csdn.net/weixin_44537992/article/details/104665482