Memory management in Object Pascal is subject to two simple rules: You must destroy every object and memory block you create and allocate, and you must
destroy each object and free each block only once. Object Pascal supports three
types of memory management for dynamic elements, here we can see a list with a quick description:
- Every time you create an object, you should also free it. If you fail to do so, the
memory used by that object won’t be released for other objects, until the program
- When you create a component, you can specify an owner component, passing the
owner to the component constructor. The owner component (often a form or
data module) becomes responsible for destroying all the objects it owns. In other
words, when you free the form, it frees all the components it owns. So, if you create
a component and give it an owner, you don’t have to worry about destroying
- When you allocate memory for strings, dynamic arrays, and objects referenced
by interface variables (as discussed Chapter 11), Object Pascal automatically frees
the memory when the reference goes out of scope. You don’t need to free a
string: when it becomes unreachable, its memory is released. Something similar
happens under ARC, as we’ll see later on.
In the most simple scenario, on desktop compilers you have to create the temporary
objects you destroy. Any non-temporary object should have an owner, be part of a
collection, or be reachable thought some data structure, which will become responsible
for destroying it in due time.
Another problem is that if you call the destructor of an object twice, you get an
error. A destructor is a method that de-allocates an object’s memory. We can write
code for a destructor, generally overriding the default Destroy destructor, to let the
object execute some code before it is destroyed. In your code, of course, you don’t
have to handle memory de-allocation—this is something the runtime library does
Destroy is a virtual destructor of the TObject class. Most of the classes that require
custom clean-up code when the objects are destroyed override this virtual method.
The reason you should never define a new destructor is that objects are usually
destroyed by calling the Free method, and this method calls the Destroy virtual
destructor (possibly the overridden version) for you.
As I’ve just mentioned, Free is simply a method of the TObject class, inherited by all
other classes. The Free method basically checks whether the current object (Self) is
not nil before calling the Destroy virtual destructor.
Be aware that Free does this:
procedure TObject.Free; begin if Self <> nil then Destroy; end;