问题
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