Reputation: 7923
I am somewhat new to the smart pointer world of C++ 11. I have been doing memory management manually and decided to dive into smart pointers. However, there is somewhat of a confusion though when it comes to managers
I define a manager as
An object that owns and manages a set of objects. The objects are exclusively owned by the manager and it's the manager's responsibly to control their life cycle (ie. delete them). It dispenses the objects for use in other parts of the program, but does not give away ownership.
In other words, it lets other parts of the program borrow the resources it manages.
What I am a little bit confused about, is how to ensure ownership is preserved by the manager?
For instance, in a videogame, a 'Sprite' might request a 'Texture' from a texture manager. The sprite doesn't own the texture, it simply wants to use it. One way to do this, is to utilize a list of unique_ptr
s. So I have:
std::list<std::unique_ptr<SpriteTexture>> _spriteTextureList;
This however doesn't work, because I cannot establish a weak_ptr
to a unique_ptr
. On the other hand, I can create a list of shared_pointers
std::list<std::shared_ptr<SpriteTexture>> _spriteTextureList;
This will allow me to dispense weak_ptr
to other parts of the program. However, the issue is that a shared_pointer can be duplicated, breaking ownership apart to multiple pointers. This of course can be controlled if I never pass back a shared pointer, but doing this seems to be counter-intuitive for what a shared_ptr
is meant to represent.
The third alternative would be to simply dispense shared_ptr
. However, this is not useful because then the manager doesn't technically own the objects. If the manager removes a Texture
out of it's list and something else has a shared_ptr
to the Texture
, then the texture wont be deleted.
In the ideal situation this should be just fine, because there should be no existing pointers to the Texture
before the manager deletes it, but I can see this becoming a debugging hassle.
I definitely have a weak understanding of smart pointers. Maybe I am miss understanding how smart pointers are supposed to be implemented?
Any help is greatly appreciated!
Upvotes: 2
Views: 1931
Reputation: 9317
If "it simply wants to use it", then SpriteTexture*
is just fine. Normal pointers are fine, as long as they don't have ownership semantics associated with them.
Just use your first solution (std::unique_ptr
) and dispense normal pointers obtained with get()
.
You just have to make sure there are no other parts of the code using such a pointer when the manager decides to get rid of the associated object, but that's the opposite problem to the one in your question. (You sort of implied this wouldn't be a problem in your application.)
A side note: I can't think of a reason to use a std::list
to hold those smart pointers. I think std::vector
should be your first choice, unless you have a specific reason not to use it here.
Upvotes: 3