[EDIT 2] It’s probably because the surface is being freed while it’s still in use by the other objects…So I want to write it so it’s only freed if no more of the object is on the screen.
[EDIT][UPDATE] I fixed the code to use the iterator, and I was still having the same issue…I just confirmed this to be an issue with the destructor for the object. In the class the destructor calls SDL_FreeSurface(image); to free the object’s image from memory…But objects created with the copy constructor apparently aren’t okay with that. What do I need to do to make it work correctly with objects created with the copy constructor? I can’t seem to find anything on Google pertaining to this.
Number refers to the number of bullets on the screen at a given time…I have a vector of the object “bullet” (vector bullet;)…The code checks if the trigger button (z) is down, and adds a new bullet to the vector if it is. Then it updates (moves, blits), then checks if the bullet is at the end of the screen…Everything works properly until a bullet reaches the end of the screen where it’s supposed to be destroyed.
if (trigger)
{
bullet.push_back(Bullet(position.x, position.y));
++number;
}
for(int i = 0; i < bullet.size(); i++)
{
bullet[i].update();
}
Below is where the issue is…When a bullet object is erased, the program exits with a segmentation fault…Now, I understand why this is happening since the vector size is changed while it’s in the loop, but I can’t figure out how to fix it…I added the break thinking that it would solve the problem since only one bullet can be <= 0 at a given time anyway, but it doesn’t…I initially had the if statement in the last for loop after the update function, but I put it in its own for loop so I could use the break.
for(int i = 0; i < bullet.size(); i++)
{
if (bullet[i].position.y <= 0)
{
bullet.erase(bullet.begin() + i);
--number;
break;
}
}
I’m new to vectors, so please bear with me here if I don’t understand something or if I’m making a n00b mistake.
The standard erase loop for sequence containers goes like this:
The use of iterators is preferable over the use of a counting index since it frees your code from counter arithmetic which adds nothing to the clarity of the code and is rather much of a nuisance, while the iterator version here presented is fairly self-explanatory.
The key is not to increment the loop variable in the event of an
erase.You may also like to look into the
remove/eraseidiom: