[fpc-pascal] For-in-loop question about GetEnumerator

silvioprog silvioprog at gmail.com
Fri May 16 23:41:58 CEST 2014


2014-05-16 18:13 GMT-03:00 Krzysztof <dibo20 at wp.pl>:

> Hi,
>
> This article is quite clear for me: http://wiki.freepascal.org/for-in_loop
>
> But let say that I have this class:
>
> TMyList = class
> private
>   FList: TList
> public
>   constructor Create;
>   destructor Destroy;
>
>   procedure Add;
>   procedure Remove;
> end;
>
> Now I want to do:
>
> for a in MyClass do
> begin
>
> end;
>
> Can I do this without creating new enumerator? I mean pass enumerator from
> FList? I'm confused because if I create function:
>
> function TMyClass.GetEnumerator: TListEnumerator
> begin
>   Result := FList.GetEnumerator;
> end;
>
> ... then FList.GetEnumerator create new object
> (TListEnumerator.Create(Self)). My question is, where it is freed? Is it
> freed automatically on runtime after exit from loop? I don't want memory
> leak
>
> Regards
>

You need to create a enumerator, and it will be freed by your owner. See
internal implementation:

Function  TComponent.GetEnumerator: TComponentEnumerator;

begin
  Result:=TComponentEnumerator.Create(Self); // Self is the owner
component, and it will free your enumerator automatically in destroy
end;

-- 
Silvio Clécio
My public projects - github.com/silvioprog
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20140516/8201c677/attachment.html>


More information about the fpc-pascal mailing list