Reputation: 2638
It is well known (???) that Delphi reference-counts interface references to interfaced objects, and destroys the objects when their reference counts drop to zero, normally because all relevant interface variables fall out of scope.
Suppose I use a global interface variable to refer to a persistent object:
type
tMySyncClass = class(TInterfacedObject,TmyInterface); ...
tMyAsyncClass = class(TInterfacedObject,TmyInterface); ...
var MyInterfaceVar : TmyInterface;
procedure MyProc();
begin
MyInterfaceVar := tMySyncClass.create();
....
MyInterfaceVar := tMyAsyncClass.create();
end
After calling MyProc
, I have an instance of tMyAsyncClass
, with one (global) MyInterface
reference to it.
Do I still have an unreferenced MySyncClass
object? Does re-assigning MyInterfaceVar
trigger destruction of the first (SyncClass
) object?
Upvotes: 1
Views: 130
Reputation: 595305
Assigning an interfaced object to an interface variable will increment the refcount of the object being assigned, and decrement the refcount of the object the variable was previously referring to.
So yes, re-assigning the MyInterfaceVar
variable will remove the reference to the tMySyncClass
object, decrementing its refcount and thus freeing the object since it has no more active references.
Upvotes: 5