Search code examples
delphigenericsmemory-leaksint64tlist

Why freeing not empty TList<Int64> does not cause memory leak?


Freeing not empty TList<Integer> does not cause memory leak because Integer is equal to pointer in size, and TList handles pointers perfectly. (This is as far as I understand it.) Freeing not empty TList<String> also does not cause memory leak, as String itself is a pointer and is carefully freed somewhere in Delphi's internals when it's no longer needed.

However, freeing any not empty TList<SomeClass> always produces memory leak, and it's understood why.

The thing I do not understand is why freeing not empty TList<Int64> does not produce memory leak.

Sorry for the noob question.


Solution

  • A TList<T> is simply a wrapper around a dynamic array of T. A dynamic array of T is a managed type and so does not need explicit destruction.

    This leaves the elements of the array. Since Int64 is a value type, it needs no explicit destruction.

    As a general rule, you need only destroy that which you created. You created the list, you need to destroy it. You did not create the elements themselves, so you do not need to destroy them.