-
Linked list
This is driving me nuts, so I came here.
Code:
class CTestTask : public ITask
{
public:
bool Start();
void Update();
void Stop();
private:
std::list < particle * > particles;
};
This is called every frame.
Code:
void CTestTask::Update()
{
for( int i = 0; i < (PARTICLES_ADDED_PER_SECOND+1; i++ )
particles.push_back( new SnowParticle );
for (std::list<particle*>::iterator part=particles.begin(); part != particles.end(); part++)
{
// We first test the particle to see if it should remain alive
//if (*part)
{
//(*part) = new SnowParticle;
if( (*part)->TestParticle() )
{
// If it should, we update and draw the particle
(*part)->UpdateParticle();
(*part)->DrawParticle();
// And then move onto the next particle
}
else
{
// If we end it here, then it continues until the point that it would have crashed, and stops making particles???
// Otherwise we cut the particle out of the list, and trash it.
delete (*part);
//particle * oldparticle = (*part);
particles.erase( part, part );
//delete oldparticle;
}
}
}
if (*part)->TestParticle() returns false, it should delete the memory for the particle and then delete the pointer from the linked list.
This causes a crash :(. If I don't free the memory from the new, then it works, but there's a memory leak...
-
If the crash is at the line where you delete the memory, then the problem might be in the destructor (I assume that particle base class has a virtual destructor). However, it looks like the erase call is what could be causing you problems. You are erasing an element in a list, then using the iterator pointing at the erased element in your next iteration. I don't think that will work. You should save a copy of the position to be erased, then increment part, then erase the saved iterator.
-
Actually, a better solution might be:
part = particles.erase(part);
part--;
Since erase returns an iterator to the next element, but you have a for loop that is incrementing on its own.
-
class Particle does NOT have a destructor other than the default. So why is deleting the memory causing a crash?
i.e.
Code:
part = particles.erase(part);
part--;
works, but
Code:
delete (*part);
part = particles.erase( part );
part--;
and
Code:
Particle * deadparticle = (*part);
part = ParticleList.erase(part);
part--;
delete (deadparticle);
do not.
-
Since particle is a base class, you must give it a virtual destructor. Deleting an object of a derived type from a pointer to the base class is undefined (meaning it could cause a crash) if the base class does not have a virtual destructor. Try adding the following to the particle class and see if it helps.
Code:
virtual ~particle() { }
EDIT - Also, if that doesn't solve it, the problem could be in any of the destructors up the inheritance chain all the way to SnowParticle.
-
thanks.
Thats gotta be it. I didn't realize thats why everybody uses virtual constructors in their classes :D
Works like a charm.