🐭 Lambda 参数捕获与上下文依赖
Lambda 参数捕获有 5 种方式,其实可以分为 3 类:
- 按值捕获,拷贝外部变量到 Lambda 内部
- 按引用捕获,在 Lambda 内部引用外部变量
- 按移动捕获,移动外部变量到 Lambda 内部
依赖上下文状态的 Lambda 表达式:
- 按引用捕获上下文变量的 Lambda 表达式
- 按值捕获上下文指针的 Lambda 表达式
不依赖上下文状态的 Lambda 表达式:
- 按值捕获上下文一般变量的 Lambda 表达式
- 按移动捕获上下文变量的 Lambda 表达式
🐂 Lambda 参数初始化捕获
在实际编码中,上下文无关的 Lambda 表达式应用更广泛,我们一般都希望我们所设计的 Lambda 表达式是自包含的,对外界的依赖越小越好。但是,按值捕获变量,有拷贝代价,按引用捕获变量有生命周期问题。总之不爽,Lambda 表达式参数初始化捕获给我们提供第三条路,即移动捕获,尤其适合对象比较大的情形。另外参数初始化捕获也可以替代按值捕获与按引用捕获,几乎可以统一 Lambda 的几种参数捕获方式。
代码示例 : ```cppinclude
int main() {
// init capture for move only object
auto up = std::make_unique
auto f2 = a = std::make_unique
// init capture instead of capture by value int a = 1; auto f3 = a { return a + b; }; auto f4 = a = a { return a + b; };
// init capture instead of capture by reference auto f5 = &a { return a + b; }; auto f6 = a = std::ref(a) { return a + b; };
return 0; }
<a name="8ixCj"></a>## 🐯 Lambda 捕获右值参数与左值参数Lambda 表达式根据其定义与调用的位置可以分为:1. 行内 lambda1. 行外 lambda行内 lambda 由于是立马调用,对于捕获的对象的生命周期一般不会出问题。<br />行外 lambda 由于定义与调用是分开的,需要注意其捕获的对象的生命周期,还要区分捕获的是右值还是左值。<br />**代码示例** :```cpp#include <iostream>#include <vector>class X {public:X(int x = 0) : x_(x){};int getX() const { return x_; };private:int x_;};// for lvalue, capture by reference for performanceauto isAGoodX(const X &lx) {std::cout << "resists(const X &xp)" << std::endl;return [&lx](const X &x) { return lx.getX() <= x.getX(); };}// for rvalue, capture by move for performance (init capture)auto isAGoodX(X &&rx) {std::cout << "resists(const X &&xp)" << std::endl;return [rx = std::move(rx)](const X &x) { return rx.getX() <= x.getX(); };}int main() {std::vector<X> XS{X{0}, X{1}, X{2}, X{3}, X{4}, X{5}, X{6}, X{7}, X{8}, X{9}};const auto xp = X{4};std::vector<X> goodXS;// inline lambdastd::copy_if(XS.begin(), XS.end(), std::back_inserter(goodXS),[&xp](X const &x) { return xp.getX() <= x.getX(); });std::cout << goodXS.size() << std::endl; // 6goodXS.clear();// out-of-line lambda and lvalueconst auto xp1 = X{4};auto const isAGoodX0 = isAGoodX(xp1);std::copy_if(XS.begin(), XS.end(), std::back_inserter(goodXS), isAGoodX0);std::cout << goodXS.size() << std::endl; // 6goodXS.clear();// out-of-line lambda and rvalueauto const isAGoodX1 = isAGoodX(X{4});std::copy_if(XS.begin(), XS.end(), std::back_inserter(goodXS), isAGoodX1);std::cout << goodXS.size() << std::endl; // 6return 0;}
:::tips 通过左值与右值的重载,我们可以让 Lambda 同时支持捕获左值与右值 :::
🐰 总结
- 使用 Lambda 参数初始化捕获来移动捕获右值对象或者只能移动的对象
- 注意行外 lambda 要支持可能到捕获左值或者右值
