Pergunta

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):

  • Do I own it and need to free it after use?
  • Or is it owned by the collection and I don't have to care about releasing it?

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;
Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top