I need a container of pointers. Would you recommend boost::ptr_vector<T>
or std::vector<boost::shared_ptr<T> >
? (Or something else?)
If that's of interest, my actual data structure is relatively complicated (see here) and currently stores objects, not pointers, but i'd like to change that (using pointer containers), in order to get rid of unnecessary copying:
typedef std::multimap<Foo0, std::map<int, double> > VecElem;
std::vector<VecElem> vec;
Who owns the object? If the container owns the objects (meaning the objects should not live longer than the container), use a ptr_vector
. Otherwise, use a vector of shared_ptr
s. Standard library containers (such as std::vector
or std::list
) own the objects they contain, so the semantics of a ptr_vector
is closer to that.
shared_ptr<>
does have a shared owner semantic, which is implemented through incrementing and decrementing of reference counts. That comes with some overhead, especially when multi-threading is enabled (because those counters then have to be locked).
If your objects are shared, use shared_ptr<>
.
But if they are effectively owned by the container, and should die with the container, and references (pointers) handed out might go dead as well when the container dies, then use pointer containers, because they have less overhead.
If you are unsure, use shared_ptr
to be on the safe side. If it turns out you have a performance problem, you can always optimize later. (It's easier to optimize a working system than to get a prematurely optimized system working.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With