user6245072 user6245072 - 1 month ago 16
C++ Question

Do I have to delete lambdas?

I am storing pointers to lambdas in dynamically allocated objects:

struct Function {
SomeType*(*func)(int);
Function(SomeType*(*new_func)(int)):
func(new_func) {}
}

Function* myf = new Function(
[](int x){ return doSomething(x); }
);

delete myf;


Do I have to write something special in the destructor of this class?

Answer

No, you do not need to do anything special. In this case (you're converting the lambda to a function pointer) this is no different to telling you that you don't need to delete doSomething either.

More generally, lambdas are unnamed types with deleted default constructors. This means you can only explicitly create one with new expression by copy/move constructing it - and only then you'd have to call delete.

N4140 ยง5.1.2 [expr.prim.lambda] /20

The closure type associated with a lambda-expression has a deleted default constructor and a deleted copy assignment operator.