delphimemory-managementdelphi-xetdictionary

Correct way to dispose of TDictionary after sorting it into an array


I have a TDictionary like

target_results : TDictionary<longint,double>;

After populating it I need to sort the results. I'm doing it like this

type
  TSearchResult = TPair<longint,double>;

var
 target_results_array : TArray<TSearchResult>;

target_results_array:= target_results.ToArray;
TArray.Sort<TSearchResult>(best_knowledge_search_results,
                    TComparer<TSearchResult>.Construct(
                              function(const L, R: TSearchResult): Integer
                              begin
                                if L.Value < R.Value then Result := 1 else if L.Value > R.Value then Result := -1 else Result := 0;
                              end
                    ));

It's all working as expected. My question is how do I dispose of the TDictionary and the TArray without any leaks? Currently I'm just doing

target_results.Free;

Solution

  • Since your data is longints and doubles, which are both value types, freeing the dictionary will work fine. Your array will contain a copy of the original values, and you don't need to worry about losing or corrupting anything.

    If you had object types instead, and you had a TObjectDictionary that owned the objects, then you'd have to worry about this sort of thing, but for purely numeric data, you're fine.