How to delete objects in a vector correctly

In my simple game engine, I have a vector containing pointers to entities. Each object is assigned a new keyword. To call functions on my objects, I use an iterator, so when deleting entities, I decided to use an iterator like this:

vector<Entity*>::iterator iter; for (iter = gameEntitys.begin(); iter != gameEntitys.end();) { delete (*iter); ++iter; } 

But now I have a terrible memory leak, and all profiling tools point to the delete (*iter);

It’s clear that there is something wrong, but for me this is the right way to delete objects contained in a vector (and clear the vector for another scene). Using gameEntitys.clear(); it is useless, as far as I know, since it only removes those elements of the vector that are not actually called to delete them, since they are pointers and not actual data.

Edit: I have a bee watching the comments. The Entity class is not polymorphic and does not have any subclasses. Would it be more reasonable if I stopped using dynamic memory and had a regular array of objects without pointers?

The reason I know is related to a memory leak, because when the application starts using memory, remove up to 2 GB before the crash.

+4
source share
1 answer

Most likely, the memory leak comes from the destructor of your Entity or one of its subclasses: you perform your delete operations correctly, so the destructor itself must be to blame. One common problem is not that destructors are virtual in the hierarchy of polymorphic classes.

You are also absolutely right about the futility of calling gameEntitys.clear() : it will leak your objects “wholesale” by “forgetting” the references to them.

If you are in C ++ 11, consider changing the definition to use std::unique_ptr

 std::vector<std::unique_ptr<Entity> > gameEntitys; 

This eliminates the need to manually manage the memory of your records, allowing you to hold pointers to objects of derived classes in vector . If you use unique_ptr , calls to gameEntitys.clear() will destroy the elements that the vector elements point to.

Working with the unique_ptr vector unique_ptr slightly different (for example, extra care is required to insert new elements, see this answer ), but I think the positives of simplified memory management compensate for the slight inconvenience.

EDIT:. Since your Entity class is not polymorphic, consider switching to std::vector<Entity> if you do not plan to move to a polymorphic hierarchy later.

+7
source

Source: https://habr.com/ru/post/1437248/


All Articles