I have this list which contains a couple of objects: ships and asteroids. To update all positions and process keys, I have this code:
Code:
std::vector<SolidObject *>::iterator item = m_objects.begin();
while(item != m_objects.end()) {
if((*item)->Update() == false) {
delete (*item);
item = m_objects.erase(item);
}
else {
item++;
}
}
This works fine, as long as my ship doesn't fire a bullet. When it does, a new object is added to m_objects:
Code:
game->AddObject(new Bullet(m_pos, m_move, m_direction, 5.0));
// AddObject is an inline function:
// inline void PlayingState::AddObject(SolidObject *item) {
// m_objects.push_back(item);
// }
AddObject is called in the ship's Update(), so something like this happens:
Code:
list: Ship, Asteroid, Asteroid, Asteroid
iterating through list:
- Ship->Update()
- A bullet is added to the list
- New list: Ship, Asteroid, Asteroid, Asteroid, Bullet
- SEGMENTATION FAULT
The segmentation fault occurs right after I fire a bullet, when (*item)->Update() is called.
I guess the problem is that the list gets altered while I'm iterating through it. Any ideas on how to fix this?