[fpc-pascal] methods of an object to create others objects
md at delfire.net
Mon Jul 5 22:03:24 CEST 2010
On Mon, Jul 5, 2010 at 4:33 PM, Martin <fpc at mfriebe.de> wrote:
> 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
None of these problems will happen, because I treat all them.
> 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;
I use this technique a lot, but thanks :) Unfortunately, this is not
The ask is:
If a function creates, inside, a object and there is no variable to
receive this pointer, will happen a memory leak?
In my eg before, this is Okay:
obj2 := obj.createObj;
The obj2 is a pointer to release.
But, like that:
obj1.createObj; //no variable to receive
...now, where is the pointer to release?
More information about the fpc-pascal