我想出了这样的代码。
将此 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) );
}
最佳答案
lambda 是一个对象,您可以按照您认为合适的方式存储它。您需要确保它所持有的任何引用或指针的生命周期。
如果您通过复制 (=
) 进行捕获,您始终是安全的。在您的示例中,您捕获 this
指针,如果该对象比您的 unique_ptr 生命周期更长(这里的情况,因为它是全局对象),这也很好。
请注意,通过指针/引用捕获本地指针或引用是一个谬误,因为它们超出了范围并变得无效,即使它们指向的对象已过期:
auto ref = this;
auto lambda = [&] () { this->… }; // ok if parent object outlives lambda
auto lambda = [&] () { ref->… }; // wrong! leads to invalid pointer
关于c++ - 将此 lambda 传递给 `unique_ptr` 可以终身使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58666104/