我应该使用boost :: ptr_vector 还是vector >?

[英]Should I use boost::ptr_vector or vector >?


I need a container of pointers. Would you recommend boost::ptr_vector<T> or std::vector<boost::shared_ptr<T> >? (Or something else?)

我需要一个容器指针。你会推荐boost :: ptr_vector 或std :: vector >吗? (或者是其他东西?)

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;

2 个解决方案

#1


30  

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.

谁拥有这个对象?如果容器拥有对象(意味着对象的寿命不应超过容器),请使用ptr_vector。否则,使用shared_ptrs的向量。标准库容器(例如std :: vector或std :: list)拥有它们包含的对象,因此ptr_vector的语义更接近于它。

#2


13  

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

shared_ptr <>确实具有共享所有者语义,这是通过递增和递减引用计数来实现的。这带来了一些开销,特别是在启用多线程时(因为那些计数器必须被锁定)。

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

如果共享对象,请使用shared_ptr <>。但是如果它们被容器有效地拥有,并且应该与容器一起死亡,并且当容器死亡时分发的引用(指针)也可能会死亡,那么使用指针容器,因为它们具有较少的开销。如果您不确定,请使用shared_ptr以确保安全。如果结果表明您遇到了性能问题,可以随时进行优化。 (优化工作系统比使过早优化的系统更有效。)

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2010/09/29/c99c6cc18a98a7df3848e5707bd527ae.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告