First of all, I understand that this is completely contrary to the purpose of shared_ptr. I am dealing with some library code where instances of ParticleSystem expect shared_ptr to pass them at build time to set the texture used for each particle. The fact is that I have already built the rest of my program in such a way that my textures have a specific property (if this is the correct term) - TextureCache owns all the textures. So I need a way to work with this ParticleSystem class, not allowing me to delete my textures. If I just created a new instance of the type ParticleSystem(std::shared_ptr<Texture>&myTexture), he would try to destroy the texture when it was destroyed (which is an undesirable and invalid operation, since my textures are not even created using new).
The cleanest way I see around this problem is something like this:
- Create shared_ptr by holding the texture in the function that creates the ParticleSystem.
- Then, using the new placement, restore shared_ptr to the same memory location as shared_ptr that I just created. Now the texture will have a reference count of 2.
- Create a particle system.
- Let shared_ptr go beyond. Its deconstructor will be called because it was allocated on the stack, and it will decrease the reference count only by 1. Thus, the reference count for an object will always be 1 more than it actually is, and therefore it will never be automatically destroyed.
I think this solution sounds, but it still seems incredibly hacky. Is there a better way to solve my problem?
source