将此lambda传递给"unique_ptr"是否可以终身使用
Is passing this lambda to `unique_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("%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
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 检查输入是否不是整数或数字
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 此代码是否违反一个定义规则
- 是否需要删除包含对象的"pair"?
- 是否可以从int转换为enum类类型
- 无论条件是否为true,if总是在c++中执行
- 如何找到大小'x'数组是否完全填充,在C++?
- 检查值是否在集合p1和p2中,但不在p3中
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- C/C++预处理器是否可以检测一些编译器选项
- "非静态数据成员之前需要构造函数" - 我是否使用"boost::variant"