Lambda 与捕获
Coddy 面向 Lua 开发者的 C++ 课程的第 24 课,共 48 课。
Lua 闭包捕获的是变量,而不是值:内部函数会保留对外部局部变量(上值)的引用,因此之后对该局部变量的赋值会被所有捕获了它的闭包看到。要冻结一个值,先将它复制到一个新的局部变量中。C++ lambda 会明确说明它如何捕获变量。[n] 会在创建 lambda 时复制该值,因此之后对 n 的更改不会被看到;[&n] 引用变量本身,这与 Lua 的行为一致。引用捕获的生命周期不能超过其引用的变量,否则调用该 lambda 会产生未定义行为。
Lua
local factor = 2
local f = function(x) return x * factor end
local snap
do
local fixed = factor
snap = function(x) return x * fixed end
end
factor = 3
print(f(4) .. " " .. snap(4))
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
int main(){
int factor=2;
auto by_value=[factor](int x){return x*factor;};
auto by_ref=[&factor](int x){return x*factor;};
factor=3;
std::cout<<by_value(4)<<" "<<by_ref(4)<<"\n";
}
移植 Lua 闭包时,先想想它是否应该看到之后的更改。如果应该,就按引用捕获,并确保变量仍然有效;如果不应该,就按值捕获。
挑战
简单第一行输入阈值,第二行输入整数。返回严格大于阈值的值的数量。
在 exercise.hpp 和 exercise.cpp 中实现已声明的 API。两个文件都可以编辑,但要保留公开签名。锁定的 main.cpp 会读取标准输入并直接调用 API。文中另有说明时,它也会独立检查公开 API 的行为。在 API 中返回值,不要打印。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。
亲手试试
#include "exercise.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
int t=std::stoi(rows[0]);std::istringstream in(rows.size()>1?rows[1]:"");std::vector<int>v;int n;while(in>>n)v.push_back(n);std::cout<<above(v,t)<<"\n";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Lua 开发者的 C++中的所有课
自己练习: C++ 在线编译器