c++ - 将此 lambda 传递给 `unique_ptr` 可以终身使用吗?

标签 c++ unique-ptr

我想出了这样的代码。

将此 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/

相关文章:

c++ - 智能指针模板

c++ - 带有数组的 unique_ptr 有什么用吗?

c++ - 替代初始化唯一指针的 vector

c++ - 如何在 Observer 中处理具有不同状态值类型的 Observable

c++ - 用cout建表,复制的代码格式不一样

C++如何检查变量是否为std::string类型?

c++ - 带有 make_unique 和 emplace_back 的简单结构

c++ - 如何创建一个新值并分配给类构造函数中的私有(private) unique_ptr?

c++ - 通过 std::unique_ptr 扩展变量的生命周期

c++ - 计算元素相对于相机的位置