我有一个类
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);
});
}
但是,它不起作用。如果OpenGLRenderer
在std::shared_ptr<Texture>
之前超出范围,那么std::shared_ptr<MemoryAllocator>
就会变得损坏,从而导致lambda表达式失控。我做错了什么?