本文介绍了Lambda捕获的变量存储在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
该示例如何运作?它显示6
:
How is it possible that this example works? It prints 6
:
#include <iostream>
#include <functional>
using namespace std;
void scopeIt(std::function<int()> &fun) {
int val = 6;
fun = [=](){return val;}; //<-- this
}
int main() {
std::function<int()> fun;
scopeIt(fun);
cout << fun();
return 0;
}
在调用scopeIt
完成后,将值6
存储在哪里?如果我将[=]
替换为[&]
,它将打印0
而不是6
.
Where is the value 6
stored after scopeIt
is done being called? If I replace the [=]
with a [&]
, it prints 0
instead of 6
.
推荐答案
它存储在闭包中,然后在您的代码中存储在std::function<int()> &fun
中.
It is stored within the closure, which - in your code - is then stored within std::function<int()> &fun
.
lambda生成的内容等同于编译器生成的类的实例.
A lambda generates what's equivalent to an instance of a compiler generated class.
此代码:
[=](){return val;}
生成与此等效的内容...这就是关闭":
Generates what's effectively equivalent to this... this would be the "closure":
struct UNNAMED_TYPE
{
UNNAMED_TYPE(int val) : val(val) {}
const int val;
// Above, your [=] "equals/copy" syntax means "find what variables
// are needed by the lambda and copy them into this object"
int operator() () const { return val; }
// Above, here is the code you provided
} (val);
// ^^^ note that this DECLARED type is being INSTANTIATED (constructed) too!!
这篇关于Lambda捕获的变量存储在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!