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

被刻印的时光 ゝ 提交于 2019-12-03 01:47:21

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!