In my simple game engine I have a vector containing pointers to entities. Each entity is allocated with the new keyword. To call functions on my entities I use an iterator and so when deleting my entities I figured I’d use an iterator as well, like so:
vector<Entity*>::iterator iter;
for (iter = gameEntitys.begin(); iter != gameEntitys.end();) {
delete (*iter);
++iter;
}
But I now have a horrific memory leak and all profiling tools point towards the line delete (*iter);
Clearly there is something wrong but what is the correct way for me to delete the entities contained in the vector (and clear the vector for another scene). Using gameEntitys.clear(); is useless to my knowledge as it only removes the elements of the vector not actually calling delete on them as they are pointers rather than actual data.
Edit: I have bee watching the comments. The Entity class is not polymorphic and does not have any subclasses. Would it make more sense if I stopped using dynamic memory and had a normal array of non-pointer entities?
The reason I know there is a memory leak is because when the application starts the memory use shoots up to more than 2gb before crashing.
Most likely, the memory leak is coming from the destructor of your
Entityor one of its subclasses: you are performing yourdeleteoperations correctly, so the destructor itself must be at fault. One common problem is not making destructors virtual in a polymorphic class hierarchy.You are also absolutely right about uselessness of calling
gameEntitys.clear(): it will leak your objects “wholesale” by “forgetting” the references to them.If you are on C++11, consider changing the definition to use
std::unique_ptrThis will free you from the need to manage the memory of your entries manually, while letting you keep pointers to objects of derived classes in your
vector. If you useunique_ptr, calls togameEntitys.clear()will destroy the items pointed to by vector’s elements.Dealing with the vector of
unique_ptris somewhat different (for example, inserting new items requires extra care, see this answer for details) but I think the positives of simplified memory management compensate for the slight inconveniences.EDIT : Since your
Entityclass is not polymorphic, consider switching tostd::vector<Entity>, unless you plan to switch to a polymorphic hierarchy later on.