[fpc-pascal] methods of an object to create others objects

Michael Van Canneyt michael at freepascal.org
Mon Jul 5 23:17:30 CEST 2010



On Mon, 5 Jul 2010, Graeme Geldenhuys wrote:

> On 5 July 2010 22:03, Marcos Douglas wrote:
>> The ask is:
>> If a function creates, inside, a object and there is no variable to
>> receive this pointer, will happen a memory leak?
>
> Yes you will have a memory leak. Easy way to test is to enable the
> heaptrc unit (compiler option -gh). On terminating the application,
> the heaptrc unit will dump memory usage output to the console window.
>
> If the object returned is a reference counted object, then I think it
> will be freed (though not working with the interface instance itself
> is bad practice).
>
> Remember FPC doesn't have garbage collection like Java or .NET.  Rule
> of thumb is that if you created it, you need to free it.

I would even add to this that you need to guard for exceptions:

A:=TSomeClass.Create;
try
   // do stuff
finally
   A.Free; Make sure it is freed, even in case of exception.
end;

If your classes have more global scope, rule of thumb is to create objects
in the form/datamodule's OnCreate event, and to free them in the OnDestroy
event. (I always code the create and free statements together, so as not to
forget this).

Michael.



More information about the fpc-pascal mailing list