简体   繁体   English

我必须删除lambdas吗?

[英]Do I have to delete lambdas?

I am storing pointers to lambdas in dynamically allocated objects: 我在动态分配的对象中存储指向lambdas的指针:

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. 在这种情况下(你将lambda转换为函数指针),告诉你不需要删除doSomething也没什么不同。

More generally, lambdas are unnamed types with deleted default constructors. 更一般地,lambdas是具有已删除的默认构造函数的未命名类型。 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 . 这意味着您只能通过复制/移动构建它来显式创建一个具有新表达式的表达式 - 然后您必须调用delete

N4140 §5.1.2 [expr.prim.lambda] /20 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. lambda表达式关联的闭包类型具有已删除的默认构造函数和已删除的复制赋值运算符。

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. 如果类直接分配动态内存(使用newmalloc [不使用malloc ]),那么您将不得不考虑如何释放该内存。 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. 因此,似乎没有任何特别的东西应该在析构函数的主体中明确地完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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