<c++> lambda的capture

本文介绍了C++11及以后版本中Lambda表达式的捕获方式,包括值传递和引用传递的差异,并展示了如何与外部变量交互。通过示例代码解释了捕获外部静态变量的规则,同时探讨了Lambda表达式内部和外部变量的作用域限制。

本文参考了侯捷老师的关于《C++标准11-14》的讲义。

capture的传值和传引用的区别

#include <iostream>
using namespace std;

int main()
{
    int id = 0;
    auto f = [id] () mutable {
        cout << "id: " << id << endl;
        ++id;
    };    
    id = 42;
    f();
    f();
    f();
    cout << id << endl;
	return 0;
}

执行结果

id: 0
id: 1
id: 2
42
#include <iostream>
using namespace std;

int main()
{
    int id = 0;
    auto f = [&id] () mutable {
        cout << "id: " << id << endl;
        ++id;
    };    
    id = 42;
    f();
    f();
    f();
    cout << id << endl;
	return 0;
}

执行结果

id: 42
id: 43
id: 44
45

capture与外部静态变量

  1. 外部静态变量要先于lambda表达式出现,才能在lambda表达式内部使用。
  2. lambda内部变量不能在外部区域使用。
#include <iostream>
using namespace std;

int main()
{
    static int id = 5;
    // 外部静态变量要先于lambda表达式出现,才能在lambda表达式内部使用。
    auto f = [] () mutable {
        cout << "id: " << id++ << endl;
        static int id2 = 10;
        cout << "id2: " << id2++ << endl;
    };   
    id = 42;
    f();
    f();
    f();
    cout << id << endl;
    // cout << "id2: " << id2 << endl; 
    // 编译不通过,error: 'id2' was not declared in this scope; did you mean 'id'?
	return 0;
}

执行结果:

id: 42
id2: 10
id: 43
id2: 11
id: 44
id2: 12
45

lambda的capture

  1. [=] means that the outer scope is passed to the lambda by value.
  2. [&] means that the outer scope is passed to the lambda by reference.

Ex:
int x=0;
int y=42;
auto qqq = [x, &y] {…};
[=, &y] to pass y by reference and all other object by value.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值