[DUG] Dumb Friday Question
karlreynolds at xtra.co.nz
karlreynolds at xtra.co.nz
Fri May 4 15:57:57 NZST 2007
>You guys don't consider a constructor a function then?
>
>I think its totally stylistic, if you want to have functions returning
>objects fine, just make it plain that they do,
>
>IMHO
>
>Neven
The downside to having "creator function"s returning objects is that you
have to duplicate the code in TObject.Create to ensure safety, as Struan
pointed out.
// Regular usage: constructor code guarantees no memory leak possibility
MyObject := TMyObject.Create;
try
...
finally
MyObject.Free;
end;
Replace TMyObject.Create with a creator function and you have to implement
its safety code again yourself:
// Function returning constructed object requires try/except to be safe
function CreateMyObject: TMyObject;
begin
...
Result := TMyObject.Create;
try
{
Any code you might put in here requires this encompassing try/except block
to prevent a memory leak occurring if an exception occurs
}
except
Result.Free;
raise;
end;
end;
And the same again for any additional levels of nesting. Not great from the
POV of encapsulation.
Cheers,
Carl
More information about the Delphi
mailing list