Just a conceptual question that I’ve been running into. In my current project it feels like I am over-using the boost smart_ptr and ptr_container libraries. I was creating boost::ptr_vectors
in many different objects and calling the transfer() method to move certain pointers from one boost::ptr_vector to another.
It is my understanding that it is important to clearly show ownership of heap allocated objects.
My question is, would it be desirable to use these boost libraries to create heap-allocated members that belong to an object but then use normal pointers to these members via get() when doing any processing.
For example…
A game might have a collection of Tiles that belong to it. It might make sense to create these tiles in a boost::ptr_vector. When the game is over these tiles should be automatically freed.
However if I want to put these Tiles in a Bag object temporarily, should I create another boost::ptr_vector in the bag and transfer the Game’s Tiles to the Bag via transfer() or
should I create a std::vector<Tile*> where the Tiles*’s reference the Tiles
in the Game and pass that to the Bag?
Thanks.
**Edit
I should point out that in my example The Game would have a Bag object as a member. The Bag would only be filled with Tiles the game owns. So the Bag would not exist without the Game.
You should only use owning smart pointers and pointer containers where there’s clear transfer of ownership. It doesn’t matter if the object is temporary or not – all that matters is whether it has ownership or not (and, therefore, whether the previous owner relinquishes ownership).
If you create a temporary vector of pointers just to pass it to some other function, and the original
ptr_vectorstill references all those objects, there’s no ownership transfer, and therefore you should use plainvectorfor the temporary object – just as you’d use a raw pointer to pass a single object fromptr_vectorto a function that takes a pointer, but doesn’t store it anywhere.