You are trying to make a backseat driver management style for memory management; you want to use shared-ptr
, but you also want to control when shared_ptr
frees up resources!
There are a few obvious things you could do here.
Just use shared_ptr
and don't worry about any memory management or resource ownership in your sprite manager class. Trust shared_ptr
to get the job done. If you need to know when a resource is destroyed, you can always use the observer pattern or the like, and your message from the resource class to the manager when it is destroyed. Of course, this means that you cannot ask your sprite manager to provide additional links to an existing sprite, which is not so large.
Write your own smart pointer. This is not necessarily trivial, but writing a special pointer for resource-oriented link counting is not rocket science (it's damn simpler than writing, for example, shared_ptr
). Then the manager can stop using the resources when there is only one link to them (for example, his own link).
Everyone else has already mentioned weak_ptr
. It has all the advantages (1), only you can create additional instances of shared_ptr
that reference the same base resource.
You can also consider resource usage patterns and resource loading costs. You may not want to destroy the resource as soon as your application stops referencing it; if it is requested again after a second, it may take some time to restart it. Lazy release of resources when they have not been used for some time may be the best approach. Just a thought.
Roook source share