Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use boost::ptr_vector<T> or vector<boost::shared_ptr<T> >?

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;
like image 416
Frank Avatar asked Sep 29 '10 14:09

Frank


2 Answers

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_ptrs. 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.

like image 168
Björn Pollex Avatar answered Nov 13 '22 15:11

Björn Pollex


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.)

like image 14
sbi Avatar answered Nov 13 '22 17:11

sbi