I'm not very comfortable with using new and delete, so I'm not quite sure if I'm doing this properly. iter is vector iterator of pointers to laser objects, and iter_ is a vector iterator of pointers to spaceship objects.
std::vector<Laser*>::iterator iter = lasers.begin();
std::vector<Spaceship*>::iterator iter_ = enemies.begin();
while (iter != lasers.end())
{
// cut out for readability
// Update enemy conditions (location/alive?)
while (iter_ != enemies.end())
{
// cut out for readability
// if the laser collides with a spaceship sprite...
if ((*iter)->isColliding((*iter_)->sprite))
{
delete *iter_; // delete the enemy
iter_ = enemies.erase(iter_);
delete *iter;
iter = lasers.erase(iter);
}
else
iter_++;
}
// Erase out-of-bounds lasers
sf::Vector2f coords = (*iter)->sprite.GetPosition();
if (coords.y >= 700 || coords.y <= -100)
{
delete *iter;
iter = lasers.erase(iter);
}
else
iter++;
}
I'm pretty sure that the problem is coming from the possibility of the laser (iter, not iter_) being deleted twice.. but if I delete and remove the laser from the vector, shouldn't it be okay since it's being reset? (The code runs fine if I comment out deleting the laser upon a collision, with the exception that the laser can plow through all the enemies on the screen)
Why are you calling delete? I might be feeling a bit slow today and I might be wrong, but erasing all three lines with delete in them might fix the problem.
I'm having problems figuring it out, but I think it's when the laser collides with something. I do know that it is those two lines that are causing it to crash.
Yeah, I think the code attempts to delete the pointer twice.
At C:\Users\...\SFML\Game Attempts\Spacefighter\Game.cpp:52
Continuing...
At C:\Users\...\SFML\Game Attempts\Spacefighter\Game.cpp:55
Continuing...
Program received signal SIGSEGV, Segmentation fault
Those two lines are the two places where I have delete *iter.
I'm still confused as to what I should do, though..
Then I wonder. Is it possible for you to forcefully move a laser to an out-of-bounds range on the map (greater than 700 in the y direction)? EDIT: If not, then try allocating a boolean and setting it to true when the laser either collides with something or goes out of bounds, and then call delete for it once. EDIT2: Guess so. ;)