# wxWidgets + Allegro + std::list = Fatal Error!!

## Recommended Posts

Escarab    103
I'm doing a clone of aero figthers(SNES), and I am in that part when I what my ship to shot some other ships. My algorithm is very simple. I will not use it in the real game, I was just testing around when I get some very strange behavior. Basicaly, it goes like this: *create a new shot(with new, I will use a pool of previously instantiated objects latter in the future). *add it to my list of current shots. *animate the shots in the list *destroy the shots that are out of screen( give then back to my pool) My problem is when I try to erase the of screen shots from my list. code:

//this is inside a wxTimer
if (key[KEY_A])
{
ship.AddShot();//put a shot in the list to be animated(new Shot)
}

list<Shot*> shots;//Shot is my shot class
ship.GetShots(shots);//grab the list with shots to be animate (reference)

if(!shots.empty())//just to be shure
{
for(list<Shot*>::iterator it=shots.begin();it!=shots.end();)
{
Shot* s=*it;
if(!s->Animate(screen))//animate returns false if shot is out
{
delete s;
it=shots.erase(it);//grabing new iterator

}
else
++it;//next iterator
}
}


What is happening: When I hit 'A', the shot goes till the end of the screen, but then, my program simply freezes, don't crash or anything, just freezes. It is not an infinity loop, task mannager shows almost 0 cpu time, I am able to close it normaly. It's like wxTimer had stop sending events. When I don't delete my shots, just erase then, everything goes just fine, but then I have a huge memory leak XD. Someone, please, enlight me.

##### Share on other sites
rip-off    10979
- why dynamically allocate "shot" instances?
- don't test for list emptiness. A normal iterator loop won't have any problems with an empty list. You are effectively doing the test twice.

I think you have a design problem

Either the ship should totally manage its shot instances, in which case it should not allow outside code to mess with their values, or the ship shouldn't manage the instances at all.

Consider:
if (key[KEY_A]){    ship.AddShot();//put a shot in the list to be animated(new Shot)}ship.animateShots(screen);// ORstd::list<Shot> shots;if (key[KEY_A]){    // returns a Shot instance    shots.push_back(ship.shoot());}// use the standard library algorithms to manage the shots.std::for_each(shots.begin(),shots.end(),animator(screen));std::remove_if(shots.begin(),shots.end(),std::mem_fun_ref(Shot::isDead()));

##### Share on other sites
Escarab    103
yeah, why allocate shots dinamicaly? It was what I said to my friend, he designed this code in the first place, I was trying to fix it without change it to much.

Thaks for your tips, I will try it as soon as i get home.