First thread on GameDev. First I shall say I am somewhat confused about my problem, hence my description might be lacking or difficult to understand. Ill try my best. In my game I have vectors of pointers to different objects, IE enemies & trees etc.
vector<Object*> allObjects;
void addObject(Unit* obj)
{
allObjects.push_back(obj);
}
addObject(new Unit(...));
Using addObject allocates an Unit to allObjects. So far everything is fine.
During the lifetime of the Unit, lots of pointers to this Unit is created at several different locations in my program. Now when this particular Unit is deallocated, I end up having lots of vectors with dangling pointers.
The only way Ive come up with to solve this is to manually keep track of every single vector containing a pointer to the Unit by having a Vector of Vectors of Units.
[source lang="cpp"]vector<vector<Unit*>* > existsInVectors;[/source]
and then in the destructor of Unit calling existsInVectors.erase(iterator to Unit). For every "send unit to vector"-function, I need to call a "RemindUnitOfThisVector"-function... I find this solution ugly, inefficient and difficult to maintain...
What would be an efficient way of having multiple vectors pointing to an instance of Unit without manually tracking what vectors the Unit is stored in? If only vectors did autoerase on dangling pointers...