Foreach Access Violation
nobody
somebody at somewhere.com
Mon Oct 20 09:05:36 PDT 2008
Say I have a class Apple:
class Apple
{
..
}
Several apples are created:
Apple[] apples;
for(int i = 0; i < 10; i++)
{
apples.length = apples.length + 1;
apples[apples.length-1] = new Apple();
}
Then I iterate over all the apples with a foreach loop
foreach(int i, Apple apple; apples)
{
apples.iterate();
}
And in the iterate() some or more apples delete themselves via
void die()
{
for (int i = 0; i < apples.length; i++)
{
if (apples[i] is this)
{
apples[i] = apples[$-1];
apples.length = apples.length - 1;
delete this;
}
}
}
This generally works fine, except when the last apple is deleted.
Then I get an Access Violation Error in the foreach loop.
When I use a for loop instead it works perfectly.
Is this because the foreach loop doesn't reevalute the length of the apples
array
while looping, or am I missing something else entirely?
More information about the Digitalmars-d-learn
mailing list