Where should a class free its private variables?

delphi, garbage-collection, memory-management

Solution

The best way to organize destruction in delphi is to always think about "who will create the given vars".

If you also free them in this context (For you private vars the destroy method of the class) it's much less likely that you will encounter memory leaks.

Actually the destructor of a class is normally not called via

myInstance.Destroy();

instead the typical way of doing it is via

FreeAndNil(myInstance);

or

myInstance.Free();

As delphi will handle calling the destructor method at order

Problem

As there is no garbage collection in Delphi, where exactly do you unload variables? Say I have a type with a set of private vars. Would it suffice to have a Destroy method that does this work? Do I need to explicitly call this destroy method in my consuming classes?

Original source

Related problems