[fpc-pascal] methods of an object to create others objects
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?
> obj1, obj2: TmyObject;
> obj1 := tobj1.create; //ok
> obj2 := obj1.createObj; // is this recommended?
This is used very often like this, so yes this is fine.
> 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:
"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.
"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:
obj1, obj2: TmyObject;
// make sure they are both initialized
// obj1.free works correct, if obj1 is nil
obj1 := nil;
obj2 := nil;
obj1 := tobj1.create;
obj2 := obj1.createObj;
More information about the fpc-pascal