是否可以将这个Lambda传递给`unique_ptr`终生可用?

缺口

我想出了这样的代码。

将此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) );
}
pn

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

C ++:将诸如unique_ptr :: get()之类的参数传递给函数是否安全?

如何将std :: unique_ptr传递给函数

将unique_ptr引用传递给boost :: bind?

将std :: unique_ptr传递给类时出错

将unique_ptr <Derived>&传递给接受unique_ptr <Base>&的函数

是否可以将lambda传递给Intent?

weak_ptr与unique_ptr参考-将接口impl传递给其他对象

将带有unique_ptr的可变lambda传递给const&std :: function

如何将NULL或nullptr传递给接收unique_ptr参数的函数?

将std :: unique_ptr传递给构造函数以获取所有权

如何将unique_ptr参数传递给构造函数或函数?

将unique_ptr的向量传递给对象。向量成为成员变量。正确的方法?

将 unique_ptr 传递给对象会引发错误

使用已使用 new X() 创建的变量将 std::unique_ptr 传递给函数

将 unique_ptr 传递给完成处理程序时提升 ASIO“错误地址”错误

如何将 unique_ptr 对象作为参数传递给作为库的类

将引用参数传递给采用 unique_ptr 的通用引用的函数

如何将包含 std::unique_ptr 的 std::optional 结构传递给函数?

传递给函数后如何使用unique_ptr?

是否可以将所有权从void *转移到unique_ptr?

为什么将匿名堆栈分配数组传递给 unique_ptr 不会导致段错误?

是否可以将const unique_ptr引用(派生类)转换为shared_ptr(基类)

是否自动将unique_ptr <Derived>转换为unique_ptr <Base>?

是否可以保证unique_ptr在移动后存储nullptr?

是否可以保证std :: unique_ptr删除顺序?

将const unique_ptr引用作为参数传递

如何将lambda用作std :: unique_ptr的Deleter?

可以将std :: unique_ptr视为monad吗?

传递unique_ptr与raw_ptr?