How is Enumerator created with for in construction destroyed?

不想你离开。 提交于 2019-12-24 05:29:23

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5039306/how-is-enumerator-created-with-for-in-construction-destroyed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!