简体   繁体   中英

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?

#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. 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).

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:

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

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