A
Alexei Polkhanov
simplier:Hanzo said:I'm iterating over a vector of base class pointers and deleting those
which meet a certain criteria...i'm using pretty text-book code for
the particular delete/erasure (it's straight out of Myers' Effective
STL), and reads like this:
void CGame::RemoveDeadObjects()
{
// cleanup crew!!
vector<CDrawableObject*>::iterator i;
for (i = g_vecGameObjects.begin(); i !=
g_vecGameObjects.end()
{
// if object is not null and can be removed...
if ((*i) && (*i)->CanRemove())
{
// grab hold before erasure
CDrawableObject* toDie = *i;
// erase...
i = g_vecGameObjects.erase(i);
// ...and kill
delete toDie;
toDie = NULL;
}
else
++i;
}
}
for (i = g_vecGameObjects.begin(); i != g_vecGameObjects.end(); ++i)
{
if ((*i) && (*i)->CanRemove())
{
delete (*g_vecGameObjects.erase(i));
}
}
to eliminate any doubts about behavior of your code just add something like
.....
~CDrawableObject(void) { std::cout << "~CDrawableObject(); " << std::endl; }
.....
to CDrawableObject class declaration, and observe output when destructor
called.
what you inserting into vector in first place is a copy of pointerHere's the problem: on the two lines that say delete toDie; toDie =
NULL; I am noticing that the original variable to which toDie is
pointing is not being set to NULL, just "toDie" itself.
.....
out of this snippet?
(variable m_cdPlayer) so when assign NULL (you should be using "0"
instead, because NULL is not defined anywhere in C++ headers) you assign
it to copy of pointer stored in a vector not to m_cdPlayer member
variable itself.
Maybe instead you should use map<>, eliminate m_cdPlayer member variable
completely and address your objects like:
.....
iter = mElemMap["CD Player"];
.....
you can iterate map<> same way as you iterate vector, only difference is
in second case, that you have only _one_ single location where you keep
pointers to Drawable objects;