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

Martin fpc at mfriebe.de
Mon Jul 5 21:33:22 CEST 2010


On 05/07/2010 19:48, Marcos Douglas wrote:
> We can to use methods of an object to create others objects, or this
> is a bad programming practice?
> eg:
> var
>    obj1, obj2: TmyObject;
> begin
>    obj1 := tobj1.create; //ok
>    obj2 := obj1.createObj; // is this recommended?
>    
This is used very often like this, so yes this is fine.

>    try
>    //...
>    finally
>      obj1.free;
>      obj2.free;
>    end;
> end;
>
> Why I ask this:
> If not exists the variable obj2 in call obj1.createObj will happen a
> memory leak, right? Because there is not variable to release.
>    
Not exactly sure what you mean?

There are 2 problems that can happen:

1)
"obj1.createObj" returns no object and obj2 will be nil, then of course 
calling obj2.foo would crash.
If "obj1.createObj"  can return nil, then you must check for this.

2)
"obj1.createObj" crashes, then you are still before the try, and obj1 
will not be freed => so yes leak


You can either do 2 nested try finally, or the following:

var
   obj1, obj2: TmyObject;
begin
   // make sure they are both initialized
   // obj1.free works correct, if obj1 is nil
   obj1 := nil;
   obj2 := nil;
   try
     obj1 := tobj1.create;
     obj2 := obj1.createObj;
   //...
   finally
     obj1.free;
     obj2.free;
   end;
end;







More information about the fpc-pascal mailing list