New linked list
Sean Kelly
sean at f4.ca
Fri May 12 09:08:30 PDT 2006
Derek Parnell wrote:
> On Fri, 12 May 2006 02:52:10 +1000, Walter Bright
> <newshound at digitalmars.com> 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.
>
> I fell for this one just yesterday. I had ...
>
> foreach( Person p; People)
> {
> Foo();
> SomeFunc(); // Potentially adds an item to the People list.
> }
>
> but the new items were never processed by Foo() !
If People is a dynamic array and adding a person to the list results in
a reallocation then I'd expect this. I would actually consider this
undefined behavior for dynamic arrays because whether a reallocation
occurs is implementation defined. But for a linked list it should work,
darnit :-)
Sean
More information about the Digitalmars-d-announce
mailing list