New linked list

Walter Bright newshound at digitalmars.com
Thu May 11 12:06:23 PDT 2006


Sean Kelly wrote:
> 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?

Yes. The idea is to apply uniform semantics.

> 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?

Yes.

> 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?

Yes.



More information about the Digitalmars-d-announce mailing list