BWG BWG - 1 year ago 63
C++ Question

Where are lambda captured variables stored?

How is it possible that this example works? It prints


#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;


cout << fun();

return 0;

Where is the value
stored after
is done being called? If I replace the
with a
, it prints
instead of

Answer Source

It is stored within the closure, which - in your code - is then stored within std::function<int()> &fun.

A lambda generates what's equivalent to an instance of a compiler generated class.

This code:

[=](){return val;}

Generates what's effectively equivalent to this... this would be the "closure":

  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!!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download