我有一个OpenGLRenderer类,它具有一个类成员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);
                                    });
}

10-04 13:30