[DUG] How's this for inconsistent

Todd todd.martin.nz at gmail.com
Wed Nov 24 16:55:14 NZDT 2010


The Delphi developer who implemented TInterfacedObject obviously 
considered the case when an interface reference is grabbed during 
construction......

// Set an implicit refcount so that refcounting
// during construction won't destroy the object.
class function TInterfacedObject.NewInstance: TObject;
begin
   Result := inherited NewInstance;
   TInterfacedObject(Result).FRefCount := 1;
end;

procedure TInterfacedObject.AfterConstruction;
begin
// Release the constructor's implicit refcount
   InterlockedDecrement(FRefCount);
end;

but didn't consider applying the same logic during destruction. So 
grabing an interface reference during destruction causes all hell to 
break loose, as the _Release method tries to free the object again and 
again recursively.

procedure TInterfacedObject.BeforeDestruction;
begin
   if RefCount <> 0 then
     Error(reInvalidPtr);
end;

function TInterfacedObject._Release: Integer;
begin
   Result := InterlockedDecrement(FRefCount);
   if Result = 0 then
     Destroy;
end;

Todd.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://listserver.123.net.nz/pipermail/delphi/attachments/20101124/05b447ab/attachment.html 


More information about the Delphi mailing list