<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="Content-Type">
</head>
<body text="#000000" bgcolor="#ffffff">
The Delphi developer who implemented TInterfacedObject obviously
considered the case when an interface reference is grabbed during
construction......<br>
<br>
<small>// Set an implicit refcount so that refcounting<br>
// during construction won't destroy the object.<br>
class function TInterfacedObject.NewInstance: TObject;<br>
begin<br>
Result := inherited NewInstance;<br>
TInterfacedObject(Result).FRefCount := 1;<br>
end;<br>
<br>
procedure TInterfacedObject.AfterConstruction;<br>
begin<br>
// Release the constructor's implicit refcount<br>
InterlockedDecrement(FRefCount);<br>
end;</small><br>
<br>
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.<br>
<br>
<small>procedure TInterfacedObject.BeforeDestruction;<br>
begin<br>
if RefCount <> 0 then<br>
Error(reInvalidPtr);<br>
end;</small><br>
<br>
<small>function TInterfacedObject._Release: Integer;<br>
begin<br>
Result := InterlockedDecrement(FRefCount);<br>
if Result = 0 then<br>
Destroy;<br>
end;</small><br>
<br>
Todd.<br>
</body>
</html>