Proper vector memory management

后端 未结 6 1139
情歌与酒
情歌与酒 2021-02-15 11:56

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:26

    That is how normally vector's memory allocation model behaves to provide an amortized constant time push_back operation, Basically it tries to guess that you might want to fill the erased part with a new element so it doesn't free the memory. By doing this it can avoid constant allocation and deallocations. To go around this, you can use the swap trick to free the unused vector memory. You have to swap your empty vector with a temporary unnamed vector so that when temporary vector goes out of scope it frees the memory in its destructor, Something like: vector(c).swap(c)

提交回复
热议问题