Lambda capture shared_ptr element

I have an OpenGLRenderer class that has a member of the mMemoryAllocator class, which is std::shared_ptr<MemoryAllocator> . The reason I save the memory allocator to shared_ptr is because even if shared_ptr<Texture> returned below selects its creator OpenGLRenderer , the MemoryAllocator instance will still be valid if I MemoryAllocator it by value, as it increases ref value quantity:

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

... but it does not work. If OpenGLRenderer goes beyond the scope to std::shared_ptr<Texture> , then std::shared_ptr<MemoryAllocator> becomes damaged, and therefore the lambda expression goes into breakers. What did I do wrong?

+7
c ++ memory-management lambda c ++ 11 smart-pointers
source share
1 answer

The problem in this case is that lambdas do not capture the elements of the object, but the this pointer. A simple workaround is to create a local variable and bind to it:

 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); }); } 
+11
source share

All Articles