user6245072 user6245072 - 9 months ago 77
C++ Question

Do I have to delete lambdas?

I am storing pointers to lambdas in dynamically allocated objects:

struct Function {
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 Source

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.