将此lambda传递给"unique_ptr"是否可以终身使用

Is passing this lambda to `unique_ptr` OK for lifetime?

本文关键字:quot 是否 unique lambda 将此 ptr      更新时间:2023-10-16

我想出了这样的代码。

将此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("%dn", 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) );
}

lambda是一个对象,您可以按照自己认为合适的方式存储它。不过,您需要确保它所包含的任何引用或指针的生存期。

如果您通过复制(=(进行捕获,则您始终处于安全的一侧。在您的示例中,您捕获了this指针,如果对象的寿命将超过您的unique_ptr(这里的情况是,因为它是一个全局对象(,这也是可以的。

请注意,通过指针/引用捕获本地指针或引用是一种谬论,因为这些指针或引用超出了范围并变得无效,即使它们指向的对象过期:

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