lambda 捕获的变量存储在哪里?

2024-02-04

这个例子怎么可能有效呢?它打印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;
}

价值在哪里6存储后scopeIt被调用完成了吗?如果我更换[=] with a [&],它打印0代替6.


它存储在闭包中,然后在您的代码中存储在闭包中std::function<int()> &fun.

lambda 生成的内容相当于编译器生成的类的实例。

这段代码:

[=](){return val;}

生成与此有效等效的内容...这将是“闭包”:

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!!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

lambda 捕获的变量存储在哪里? 的相关文章

随机推荐