New linked list
Sean Kelly
sean at f4.ca
Thu May 11 10:39:24 PDT 2006
Walter Bright wrote:
> Sean Kelly wrote:
>> Very cool. One thing... does this work:
>>
>> foreach( Person p; per.each )
>> {
>> if( p.age > 50 )
>> p.listRemove();
>> }
>>
>> ie. can you remove elements within a foreach?
>
> It's undefined behavior. foreach is entitled to assume that the
> aggregate is a loop invariant, although the contents of the aggregate's
> elements can change. This precludes things like resizing an array inside
> a foreach, etc.
Even for a class that defines an opApply? What about an alternate syntax:
foreach( Person p; personList )
{
if( p.age > 50 )
personList.remove( p );
}
Assuming the list code supports this operation (say the 'next' pointer
isn't set to null when p is removed, and thus the iteration should
continue without any problems), is the behavior still undefined? If so,
I assume it would be okay to store a list of 'removed' items until the
iteration ends and them remove them all at once?
Sean
More information about the Digitalmars-d-announce
mailing list