Deleting Pointers from STL Vector

A

Alexei Polkhanov

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;
}
}
simplier:

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.
Here'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?
what you inserting into vector in first place is a copy of pointer
(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;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top