Do I need to free the counter returned by GetEnumerator?

I want to use an enumerator for a general collection with Delphi XE2. I am wondering who owns the TEnumerator returned by the GetEnumerator function (I did not find a clear answer in the documentation):

  • Do I own it and should I release it after use?
  • Or does it belong to the collection, and I do not need to worry about its release?

the 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; 
+4
source share
1 answer

If you look at the source of a TDictionary, you will find that GetEnumerator (at its ancestor) calls DoGetEnumerator, which in TDictionary calls a re-entered version of GetEnumerator.

The re-entered TDictionary.GetEnumerator creates an instance of TPairEnumerator, which is passed as a dictionary to enumerate. The dictionary does not contain a link to TPairEnumerator. PairEnumerator does not receive notification of the destruction of its dictionary.

So yes, you need to free up the counter and avoid any access violations that you really have to do before destroying the dictionary that it lists.

+6
source

Source: https://habr.com/ru/post/1401572/


All Articles