Foreach Access Violation
somebody at somewhere.com
Mon Oct 20 09:05:36 PDT 2008
Say I have a class Apple:
Several apples are created:
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)
And in the iterate() some or more apples delete themselves via
for (int i = 0; i < apples.length; i++)
if (apples[i] is this)
apples[i] = apples[$-1];
apples.length = apples.length - 1;
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
while looping, or am I missing something else entirely?
More information about the Digitalmars-d-learn