the correct way to delete a map

R

Roland Pibinger

Which classic C++ idiom. When the object is conceptually
"owned" by another object, that object deletes it. When the
object doesn't have an owner, it deletes itself.


That works in a few limited cases, but most entity objects have
lifetimes which are independant of scope or of any other object.

I have had a contrary experience. It's more a matter of design than an
implementation limitation. When you design an application with
'Creator As Sole Owner' and RAII in mind things fall into place quite
naturally and questions like 'which is the right scope for an owner'
are easy to answer.
 
J

James Kanze

I have had a contrary experience. It's more a matter of design than an
implementation limitation. When you design an application with
'Creator As Sole Owner' and RAII in mind things fall into place quite
naturally and questions like 'which is the right scope for an owner'
are easy to answer.

In other words, if you force your design to something unnatural,
you can make anything work. "Creator As Sole Owner" is
certainly not OO. (Neither is RAII, for that matter, but RAII
doesn't normally concern entity objects per se, but rather
transaction mnanagement.)
 
J

Joel Yliluoma

for (map::iterator itr = myMap.begin(); itr != myMap.end())
{
if(itr->value == something)
myMap.erase(itr++);
else
itr++;
}

for(map::iterator j, i = myMap.begin(); i != myMap.end(); i = j)
{
j = i; ++j;

if(i->value == something)
myMap.erase(i);
}

This is how I do it as I wasn't aware of erase() returning an
iterator (which apparently may be the case in some implementations).

If you want to avoid the redundant default constructor
call of j, then write it as follows:

for(map::iterator i = myMap.begin(); i != myMap.end(); )
{
map::iterator j = i; ++j;

if(i->value == something) myMap.erase(i);

i=j;
}

However, this code is more prone for errors: for example,
if you use "continue;", it will omit "i=j;", causing an
infinite loop at worst.
 
J

Joel Yliluoma

for (map::iterator itr = myMap.begin(); itr != myMap.end())
{
if(itr->value == something)
myMap.erase(itr++);
else
itr++;
}

for(map::iterator j, i = myMap.begin(); i != myMap.end(); i = j)
{
j = i; ++j;

if(i->value == something)
myMap.erase(i);
}

This is how I do it as I wasn't aware of erase() returning an
iterator (which apparently may be the case in some implementations).

If you want to avoid the redundant default constructor
call of j, then write it as follows:

for(map::iterator i = myMap.begin(), j = i; i != myMap.end(); i = j)
{
++j;
if(i->value == something) myMap.erase(i);
}
 

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

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,228
Latest member
MikeMichal

Latest Threads

Top