Calling Free
on a null link is always safe. Go to the TObject.Free
implementation to see why.
This code is an example of a factory function. Its task is to create a new instance of the class, but if it fails, it needs to make sure that it does not leak the semi-delivered instance when it throws an exception, so it throws Free
. When he is sure that it will be successful, it transfers ownership of the result to the caller. It still calls Free
, but if it has already transferred ownership, it ends the Free
call with a null reference, and no harm is done. This code transfers ownership:
Result := Connection; Connection := nil;
The way I write the factory function will delete a separate Connection
variable. I would build the result directly in Result
, but release it if an exception occurred, for example:
function TDBXConnectionFactory.GetConnection(const DBXContext: TDBXContext; const ConnectionProperties: TDBXProperties): TDBXConnection; var ConnectionBuilder: TDBXConnectionBuilder; DelegatePath: TDBXDelegateItem; Connection: TDBXConnection; CombinedProperties: TDBXProperties; begin //... ConnectionBuilder := TDBXConnectionBuilder.Create; try //..lots of setting ConnectionBuilder properties ConnectionBuilder.FInputPassword := CombinedProperties[TDBXPropertyNames.Password]; Result := ConnectionBuilder.CreateConnection; try Result.Open; except Result.Free; raise; end; finally ConnectionBuilder.Free; end; end;
This has the same effect.
Rob kennedy
source share