TDictionary, how to destroy it

I have tried every way to Destroy TDictionary but whenever I have the ReportMemoryLeaksOnShutdown active it always leaves something without being destroyed. I've tried running the list and destroying item by item.

Code:

with foDict.GetEnumerator do
  while MoveNext do
    Current.Value.Free;

foDict.Free;

As I tried to also destroy only the foDict.Free;

Both memory leaks. Does anyone have any suggestions?

Author: Tmc, 2016-11-03

3 answers

Using your example, the code would have the following changes:

New Class:

TMyCustomDictionary = TObjectDictionary<integer, TCliente>;

New use of foDict object:

foDict: TMyCustomDictionary;

New Create of foDict object

foDict := TMyCustomDictionary.Create([doOwnsValues]);

Once this is done, the button FreeList, becomes no longer useful

 2
Author: Victor Tadashi, 2016-11-03 19:32:25

Tests as follows::

destructor TMemCorrectedDictionary.Destroy;
begin
  inherited;
  Values.Free;
  Keys.Free;
end;

More information here: Memory Leak in TDictionary-Problems with Workaround?

 0
Author: Tmc, 2017-10-13 11:58:46

Yes, with TObjectDictionary you can use .Create ([doOwnsValues]) that free all objects automatically. [doOwnsValues] is not possible to TDictionary, you need to do manually.

 -2
Author: Roberto Novakosky, 2020-10-28 23:24:22