Hi Martin On Mon, Jul 5, 2010 at 4:33 PM, Martin <f...@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? >> 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
None of these problems will happen, because I treat all them. > 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; I use this technique a lot, but thanks :) Unfortunately, this is not the *problem*. 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? Marcos Douglas _______________________________________________ fpc-pascal maillist - fpc-pascal@lists.freepascal.org http://lists.freepascal.org/mailman/listinfo/fpc-pascal