c++ - Lambda 捕获 shared_ptr 成员

标签 c++ memory-management c++11 lambda smart-pointers

我有一个类OpenGLRenderer它有一个类(class)成员mMemoryAllocator那是一个std::shared_ptr<MemoryAllocator> .我将内存分配器保留在 shared_ptr 中的原因是因为即使 shared_ptr<Texture>下面返回的时间超过了它的创建者 OpenGLRenderer , MemoryAllocator如果我按值捕获实例,实例仍然有效,因为它会增加引用计数:

std::shared_ptr<Texture> OpenGLRenderer::CreateTexture(TextureType textureType, const std::vector<uint8_t>& textureData, uint32_t textureWidth, uint32_t textureHeight, TextureFormat textureFormat)
{
    return std::shared_ptr<Texture>(mMemoryAllocator->AllocateObject<Texture>(
                                    textureData, textureWidth, textureHeight,
                                    textureFormat, textureType, mLogger), 
                                    [=](Texture* texture) { 
                                        mMemoryAllocator
                                         ->DeallocateObject<Texture>(texture); 
                                    });
}

...但是,它不起作用。如果OpenGLRendererstd::shared_ptr<Texture> 之前超出范围, std::shared_ptr<MemoryAllocator>变得损坏,因此 lambda 表达式变得疯狂。我做错了什么?

最佳答案

这种情况下的问题是 lambda 不捕获对象的成员,而是捕获 this 指针。一个简单的解决方法是创建一个局部变量并绑定(bind)它:

std::shared_ptr<Texture> 
OpenGLRenderer::CreateTexture(TextureType textureType, 
                              const std::vector<uint8_t>& textureData, 
                              uint32_t textureWidth, uint32_t textureHeight, 
                              TextureFormat textureFormat)

{
    std::shared_ptr<AllocatorType> allocator = mMemoryAllocator;
    return std::shared_ptr<Texture>(mMemoryAllocator->AllocateObject<Texture>(
                                    textureData, textureWidth, textureHeight,
                                    textureFormat, textureType, mLogger), 
                                    [=](Texture* texture) { 
                                        allocator
                                         ->DeallocateObject<Texture>(texture); 
                                    });
}

关于c++ - Lambda 捕获 shared_ptr 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19528375/

相关文章:

C++ 程序...过冲?

java - 跨编程语言的动态内存分配

c++ - hashmap 的内存高效数据结构 (c++)

c - C 中的动态 char** 数组

python 将整数传递给 C++ 64 位库 : varying sizes

c++ - 如何确定 std::future 是否有值?

c++ - 是否可以使用 std::unique_ptr 来管理 DLL 资源?

c++ - 将局部变量声明为右值引用是否无用,例如T&& r = move (v)?

c++ - 将右值引用实现为函数重载中的参数

c++ - 英特尔 C++ 编译器是否优化了代码中从未调用过的函数?