shrink_to_fit() vs swap trick

强颜欢笑 提交于 2021-02-16 05:54:14

问题


I have a game where certain game objects spawn all at once and then despawn as they get destroyed/killed. The game objects are elements in an std::vector, and I'd like to minimize memory usage. I'm used to the swap trick,

std::vector<gameObject>(gameObjectVector.begin(), gameObjectVector.end()).swap(gameObjectVector);

but I noticed the inbuilt shrink_to_fit() from C++11. However, it has linear complexity while the swap trick is constant. Isn't the swap trick superior in every way?


回答1:


The swap trick isn't actually constant-time. The cost of performing the actual swap is indeed O(1), but then there's the cost of the std::vector destructor firing and cleaning up all the allocated space. That can potentially have cost Ω(n) if the underlying objects have nontrivial destructors, since the std::vector needs to go and invoke those destructors. There's also the cost of invoking the copy constructors for all the elements stored in the initial vector, which is similarly Ω(n).

As a result, both approaches should have roughly the same complexity, except that shrink_to_fit more clearly telegraphs the intention and is probably more amenable to compiler optimizations.




回答2:


Accepted answer that also got featured on isocpp.org is wrong.

shrink_to_fit is nonbinding requirement. I personally I think it is idiotic from ISO to leave this as nonbiding(without providing some stronger guarantees about what happens) since it is confusing, but maybe they had good reasons(tm).



来源:https://stackoverflow.com/questions/43667175/shrink-to-fit-vs-swap-trick

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