-1

Where do lambdas and std::functions store variables captured by value?

int i = 1;
auto l = [i](void) mutable { return i++; };
std::function<int(void)> f = l;

Do they call the new operator? If I provide my own new operator, will it be used by lambdas?

haael
  • 972
  • 2
  • 10
  • 22
  • Lambdas are classes that save variables as member data and `std::function` just saves the lambda. Depending on the size of the callable object it either fits inside the `std::function` or sits on the heap. – nwp Oct 16 '15 at 12:51

2 Answers2

0

From [expr.prim.lambda] 5.1.2(15)

An entity is captured by copy if it is implicitly captured and the capture-default is = or if it is explicitly captured with a capture that is not of the form & identifier or & identifier initializer. For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The declaration order of these members is unspecified. The type of such a data member is the type of the corresponding captured entity if the entity is not a reference to an object, or the referenced type otherwise. [ Note: If the captured entity is a reference to a function, the corresponding data member is also a reference to a function. β€”end note ] A member of an anonymous union shall not be captured by copy.

emphasis mine

So a variable captured by value will be stored as member of the closure type. The closure type is unspecified as per 5.1.2(3)

The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed nonunion class type β€” called the closure type β€” whose properties are described below. This class type is neither an aggregate (8.5.1) nor a literal type (3.9). The closure type is declared in the smallest block scope, class scope, or namespace scope that contains the corresponding lambda-expression.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
0

At compile time lambdas are actually turned into classes. So if you had the following.

int a; Widget widget; 

auto somelambda = [=a,&widget](){

}

You could actually think of it as

class SomeLambda
{
int a;
Widge& w;
...
}

Which should make you really cautious because you can have dangling references.

Freddy
  • 2,249
  • 1
  • 22
  • 31