I want to use the enumerator for a generic collection with Delphi XE2. I am wondering, who owns the TEnumerator returned by the function GetEnumerator (I haven't found any clear answer in the documentation):
Code:
procedure Test;
var
myDictionary: TDictionary<String, String>;
myEnum: TDictionary<String, String>.TPairEnumerator;
begin
{ Create a dictionary }
myDictionary := TDictionary<String, String>.Create;
myDictionary.Add('Key1', 'Value 1');
myDictionary.Add('Key2', 'Value 2');
{ Use an enumerator }
myEnum := myDictionary.GetEnumerator;
// ... do something with the Enumerator ...
{ Release objects }
myEnum.Free; // ** Do I need to free the enumerator? **
myDictionary.Free;
end;
If you look at the source of TDictionary, you will find that GetEnumerator (in its ancestor) calls DoGetEnumerator which in TDictionary calls a reintroduced version of GetEnumerator.
The reintroduced TDictionary.GetEnumerator creates a TPairEnumerator instance passing itself as the dictionary to be enumerated. The dictionary does not hold a reference to the TPairEnumerator. The PairEnumerator does not get notified of the destruction of its dictionary.
So, yes you do need to free the enumerator yourself and to avoid any access violations you really should do that before destroying the dictionary that it enumerates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With