8

我有一个类OpenGLRenderer,它的类成员mMemoryAllocatorstd::shared_ptr<MemoryAllocator>. 我将内存分配器保留在 shared_ptr 中的原因是,即使shared_ptr<Texture>下面返回的比它的创建者寿命更长,如果我按值捕获它OpenGLRendererMemoryAllocator实例仍然有效,因为它会增加 ref 计数:

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); 
                                    });
}

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

4

1 回答 1

11

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

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); 
                                    });
}
于 2013-10-22T21:14:03.503 回答