How to free a generic TList<T>?

delphi, generic-list, generics

Solution

Executive summary

`MyList.Free` is sufficient.

Detailed answer

The `TList<T>` generic container owns its contents. When you free the container, the contents are also disposed of.

Now, if `T` is an unmanaged reference, either a pointer or a class, then the list owns the reference. It does not own that which the reference refers to. So if you have `TList<TObject>`, add some objects, and then free the list, the references are disposed of, but the objects remain. So, to deal with this there is `TObjectList<T>`. That container can be configured to own the objects as well as the references, and so dispose of the objects at the appropriate moment.

Now, in your scenario, each of your lists contains either a value type, or a managed type. The list owns those objects and disposes of them when it is destroyed. So for all of your lists, `MyList.Free` is all that is needed.

Problem

Does freeing generic lists like `TList<string>`, `TList<Double>`, `TList<Integer>` or `TList<TMyRecord>`, where `TMyRecord` is declared like: ``` type TMyRecord = record MyString: string; MyDouble: Double; MyInteger: Integer; end; ``` require any additional work or is `MyList.Free` sufficient ?

Original source

Related problems