Proper vector memory management

后端 未结 6 1255
面向向阳花
面向向阳花 2021-02-15 12:08

I\'m making a game and I have a vector of bullets flying around. When the bullet is finished, I do bullets.erase(bullets.begin() + i); Then the bullet disappears. However it doe

6条回答
  •  自闭症患者
    2021-02-15 12:23

    First, std::vector erase method is not very effecient, it has to move all items after the deleted one. If order of vector items (bullets) does not matter, swapping the deleted bullet with the last bullet and deleting the last bullet will be faster (so you get constant complexity instead of linear complexity).

    Second, what is the real problem - that after deletion of the 10,000 items, memory is not freed up? Are we talking about free memory reported by operating system, or free space on the heap? It is possible (and very likely), that some other object was allocated after the position of the data of the vector, so it is not possible to simply free this memory to operating system; but it can be reused for other, newly created objects.

提交回复
热议问题