Im using a STL vector in my SDL program. and it looks like this: vector< Bullet * > vec; this makes a vector that can contain pointers to Bullet objects. when i run my program i only add one item开发者_StackOverflow中文版 at a time using: vec.push_back( new_bullet ); (new_bullet is a pointer to a "new" Bullet object. then in a following function i erase an object using: vec.erase(...); vec.size() shows that the items are being pushed and popped properly. I'm running Ubuntu 9.10 and System Monitor shows my programs memory usage slowly increasing. Is it my program or something I'm missing about STL vector?
Sounds like you're not delete
ing the "bullet" objects as you remove them from the vector.
erase()
only removes an element from a vector, it does not delete the memory pointed to if that element is a pointer. This makes sense... imagine you had a vector<const char *>
of string literals and did v.erase(i)
; you can't delete a const char *
!
However, erase()
will call the destructor for the element removed. So if you used a sort of "pointer object" rather than a pointer, it could release the memory when destroyed. If you're interested, you should check out boost::shared_ptr
which implements reference counted garbage collection.
If you're only adding to the end of the array and you're worried about memory fragmentation, you might want to use std::list
instead. The only problem is, list accesses are O(n) time if they're not at the beginning.
Are you calling free()/delete on your bullets when you're done with them after pulling them out of the vector?
While I'm guessing the original poster is not freeing his "popped" pointers (pop doesn't do that for you), std::vector has another "feature" that may cloud it issue. std::vector overallocate space such that every push_back doesn't entail a reallocation and copy of the existing contents. In other words, the space used for vector is generally more than what's returned by .size().
Take a look at the shrink-to-fit idiom if you wish to make a std::vector take up no more space than it needs to hold its elements. Not useful if you are constantly manipulating the vector, but once you have everything loaded, it can save some space.
精彩评论