第一眼看到[]这玩意不知道是啥,感觉贼难
后来看到lambda感觉很像js,实际上就是让C++支持高阶函数吧
我的目的是做一个 求n!(n<10)的 函数,自带缓冲数组
在javascript中,可以通过闭包来实现这个功能
首先 capture ref举个例子
#include<iostream>
#include<functional>
std::function <void()> p()
{
int i = 10;
return [&]() {
std::cout << i;
};
}
int main()
{
auto f1 = p();
f1();
return 0;
}
这个程序的结果
实际上,在auto f1=p();执行结束后,i便被销毁。
无法延长作用域,所以应当是= copy操作
在看capture value的例子
#include<iostream>
#include<functional>
std::function <void()> p()
{
int i = 10;
return [=]() mutable{ //这个mutable 意为捕获的value可修改 否做无法编译(提示i必须是可更改的左值)
std::cout << i++<<" ";
};
}
int main()
{
auto f1 = p();
f1();
f1();
f1();
return 0;
}
看到这个 就有点闭包的感觉了 嘻嘻:)
这个i 并不是函数p()中真正声明的i 那个old i已经被销毁
是p()的返回函数中 通过临时变量copy的一个new i 这个copy应该发生在auto f1 = p();这行中;
而且 达到了 延长变量i作用域的目的;
这里是目的程序
#include<iostream>
#include<functional>
std::function <int(int)> p()
{
int a[10] = { 0 };
return [=](int n)mutable {
if (a[n])
{
std::cout << "读取缓冲数据得出:";
return a[n];
}
else {
a[n] = 1;
int temp = n;
while (temp >= 1)
{
a[n] *= temp;
temp--;
}
std::cout << "首次输入,通过计算得出:";
return a[n];
};
};
}
int main()
{
int k;
auto lf = p();
while (std::cin >> k)
{
if (k >= 10)break;
std::cout << lf(k) << std::endl;
}
return 0;
}
通过capture value
一个很人性化的设计
When the lambda-expression is evaluated, the entities that are captured by copy are used to direct-initialize each corresponding non-static data member of the resulting closure object. (For array members, the array elements are direct-initialized in increasing subscript order.)
这里的对于临时变量初始化,并不是赋值的地址
类似于memcpy函数,是对每个数组以递增下标方式进行初始化
美滋滋:)
之后看到这个
Benjamin Lindley provided an answer about declaration of lambdas in C++.
But technically speaking you cannot reproduce JavaScript closures using C++ lambdas.
In JS outer variables that used by local function are protected by GC mechanism.
But in C++, if you capture variables by reference, you can easily get into situation when referenced variables are destroyed and you'll get segmentation fault / access violation.
意思我们不能在技术上实现javascript上面的C++ lambdas闭包
如果是这样还希望 能给予指正 博主很菜,了解的闭包还很浅显:)
参考: https://www.reddit.com/r/cpp/comments/4t5kcd/capturing_an_array_in_c_lambda/
https://stackoverflow.com/questions/20754408/c-lambda-value-cant-capture
https://stackoverflow.com/questions/20754408/c-lambda-value-cant-capture