简体   繁体   English

将这个 lambda 传递给 `unique_ptr` 是否可以终身使用?

[英]Is passing this lambda to `unique_ptr` OK for lifetime?

I come up with code like this.我想出了这样的代码。

Is passing this lambda to unique_ptr in method ptr OK for lifetime?将此 lambda 传递给方法ptr中的unique_ptr是否可以终身使用?

#include <memory>

#include <cstdlib>

#include <cstdio>

struct MallocAllocator{
    static void *allocate(size_t size) noexcept{
        return malloc(size);
    }

    /* static */ void deallocate(void *p) noexcept{
        printf("%d\n", x); // debug
        return free(p);
    }

    template<class T>
    auto ptr(T *p){
        auto x = [me = this](T *p){
            me->deallocate(p);
        };

        return std::unique_ptr<T, decltype(x)>{ p, x };
    }

    int x; // debug

    MallocAllocator(int x) : x(x){}
};

MallocAllocator allocator{5};

int *getInt(MallocAllocator &allocator){
    return (int *) allocator.allocate(sizeof(int));
}

int main(){
    auto a = allocator.ptr( getInt(allocator) );
}

A lambda is an object and you can store it how you see fit. lambda 是 object,您可以按照您认为合适的方式存储它。 You need to ensure the lifetime of any references or pointers it holds though.您需要确保它拥有的任何引用或指针的生命周期。

If you capture by copy ( = ) you are always on the safe side.如果您通过副本 ( = ) 捕获,则始终是安全的。 In your example, you capture this pointer, which is also fine if the object will outlive your unique_ptr (the case here as it is a global object).在您的示例中,您捕获this指针,如果 object 的寿命超过您的 unique_ptr (这里的情况是全局对象),这也很好。

Note that it is a fallacy to capture local pointers or references by pointer/reference because these fall out of scope and get invalid, even if the object they point to outlives:请注意,通过指针/引用捕获本地指针或引用是一种谬误,因为它们从 scope 中脱落并变得无效,即使它们指向的 object 寿命更长:

auto ref = this;
auto lambda = [&] () { this->… }; // ok if parent object outlives lambda
auto lambda = [&] () { ref->… }; // wrong! leads to invalid pointer

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

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