简体   繁体   中英

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?

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.

Without knowing what your class is supposed to do, it is impossible to tell you what its destructor should or shouldn't do.

If the class directly allocates dynamic memory (with new or malloc [don't use malloc ]), then you would have to consider how to deallocate that memory. Likewise, if the class acquires other resources such as file pointers, you will have to consider how to release those resources. Typically, the proper place to do that is the destructor.

Ask yourself: Does the class directly allocate any dynamic memory or aquire external resources? Answer appears to be: No, it doesn't. So there appears to not be anything in particular that should be explicitly done in the body of the destructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM