7.8 Reference counting

All COM interfaces use reference counting. This means that whenever an interface is assigned to a variable, its reference count is updated. Whenever the variable goes out of scope, the reference count is automatically decreased. When the reference count reaches zero, usually the instance of the class that implements the interface, is freed.

Care must be taken with this mechanism. The compiler may or may not create temporary variables when evaluating expressions, and assign the interface to a temporary variable, and only then assign the temporary variable to the actual result variable. No assumptions should be made about the number of temporary variables or the time when they are finalized – this may (and indeed does) differ from the way other compilers (e. g. Delphi) handle expressions with interfaces. E. g. a type cast is also an expression:

Var  
  B : AClass;  
 
begin  
  // ...  
  AInterface(B.Intf).testproc;  
  // ...  
end;

Assume the interface intf is reference counted. When the compiler evaluates B.Intf, it creates a temporary variable. This variable may be released only when the procedure exits: it is therefore invalid to e. g. free the instance B prior to the exit of the procedure, since when the temporary variable is finalized, it will attempt to free B again.

Additionally, function results may point to a non-nil valid COM interface on entry: this is because the function result is treated as a var parameter.