我想出了这样的代码。
将此lambda传递给unique_ptr
方法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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句