Reputation: 31
I'm attempting to make an algorithm that can draw the entities of my isometric game in the correct order. My entities are stored in a vector of pointers.
In the drawing function I first create a new vector of the same pointers, and then start with a for-loop that loops the amount of entities that I want to have drawn. Inside that loop there is yet another loop, which determines what entity to be drawn, and when an entity is drawn it's pointer is removed from the vector using vector.erase(), so the same entity wont be drawn twice (Which is why I'm creating a copy of the vector that is containing the entity pointers).
Anyway, my code itself works, and the entities are drawn the way I want, but I appear to have a memory leak (I can actually see the memory in the Windows Task Manager climb by 28 kb/s).
The memory leak remains even if I outcomment everything except this:
vector<Entity*> list = ent_list; // ent_list is the list of entity pointers
list.clear();
So I guess I'm missing something, but I'm not sure what. I figured since I didn't use "new" the memory would be taken care of, but obviously it isn't... Hope someone can help me!
/feodor
Upvotes: 3
Views: 3923
Reputation: 54158
The easiest way to correct this is to replace the container element with boost::shared_ptr<Element>
. This will probably clean up the code that uses the vector as well and provide a pointer to better memory management standard practice down the line.
Upvotes: 0
Reputation: 5705
The vector will not delete the memory behind your pointers. You'll have to delete each Entity* before calling clear() or you could use a "smart container" as the boost::ptr_vector.
Upvotes: 1
Reputation: 39906
No, standard containers only erase the memory they have created;
std::list.clear();
will only invalidates and remove the iterators themselves, not the memory you have allocated.
you have to call std::list.remove()
or std::list.erase()
each iterator after another, and manually delete the pointers you had allocated yourself.
Upvotes: 1
Reputation: 1799
Reference for vector::clear says: "if the elements of the vector are pointers to objects, this function will not call the corresponding destructors". Are you sure you're not relying on this?
Upvotes: 4