2

I have a collection derived from TCollection, implementing GetEnumerator so I can use it in a construction like

for lElem in lCollection do

The enumerator is derived from TObject, exactly like the standard enumerators supplied by Delphi and therefor doesn't have an owner.

The Delphi help mentions that if the enumerator supports IDisposable is it will be disposed of, but that is for .NET only of course.

What I was wondering is, how and when and by who the enumerator instance is freed?

menjaraz
  • 7,551
  • 4
  • 41
  • 81
Bascy
  • 2,017
  • 1
  • 21
  • 46

2 Answers2

6

For each for-enum statement compiler generates code that roughly corresponds to this pseudocode:

enumerator := list.GetEnumerator;
try
  while enumerator.MoveNext do
    do something with enumerator.Current;
finally
  enumerator.Free;
end;

The code above is generated for enumerators that are implemented as class instances. If your enumerator is implemented as an interface, the last line would not call .Free but merely decrement interface reference count allowing it to be destroyed.

gabr
  • 26,580
  • 9
  • 75
  • 141
  • Actually, it is in an implicit `try...finally` block; the actual generated code also depends on the kind of enumerator (class, record or interface). Oh and I know about the "actually thing" http://twitter.com/#!/migueldeicaza/status/38420006018486272 – Jeroen Wiert Pluimers Feb 18 '11 at 10:49
  • @Jeroen: I was trying to be concise but there's always somebody that complains ... ;) – gabr Feb 18 '11 at 11:02
  • 1
    I presume the try/finally is skipped when you are using a record, well so long as the record contains no managed types itself – David Heffernan Feb 18 '11 at 11:23
  • 1
    It is. The example above was for class-based enumerators. – gabr Feb 18 '11 at 11:44
  • @gabr and presumably you've deduced all this by reverse engineering? Am I right in my assertion that this is not documented, is an implementation detail and is subject to change in a future release? – David Heffernan Feb 18 '11 at 11:59
  • I remember a session, but forgot it was by Danny Thorpe or someone else from the Delphi team, mentioning the try...finally thing. – Jeroen Wiert Pluimers Feb 18 '11 at 12:22
1

It's freed automatically once it is no longer needed. The compiler generates code to do that so that you don't need to. When the disposal happens is an implementation detail.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490