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

Marcos Douglas md at delfire.net
Tue Jul 6 16:56:15 CEST 2010

On Mon, Jul 5, 2010 at 6:06 PM, Graeme Geldenhuys
<graemeg.lists at gmail.com> 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.

I didn't know that, thanks for the tip!

On Mon, Jul 5, 2010 at 6:17 PM, Michael Van Canneyt
<michael at freepascal.org> wrote:
> 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).

I always do that, but thanks!

On Mon, Jul 5, 2010 at 7:39 PM, Andrew Brunner
<andrew.t.brunner at gmail.com> wrote:
> If Memory allocation is the point of discussion and you need to create
> objects ...
> You should nest the creations in order of usage.
> In your declarations you needed bot Object1 and Object2 as TMyObject;
> That said the proper usage would be:
> obj1:=TMyObject.Create;
> Try
>  obj2:=TMyObject.Create;
>  Try
>    Obj1.DoSomething1;
>    Obj2.DoSomething2;
>   Finally
>     FreeAndNil(Obj2);
>   end;
>  Finally
>   FreeAndNil(Obj1);
> end;

Hum... I do not agree. Why not this? See..


> I would like to know what the purpose is for having an auxiliary
> constructor if they both reference createObj.

If your object have a simple constructor, ok... do not need... but did
you see my example before? An object Parser, reading text in a file
and creating objects through these lines of text?

Marcos Douglas

More information about the fpc-pascal mailing list