Counting references


Let’s take another look at the B-- implementation of CHardway. Our first look concentrated on QueryInterface. This time we’ll focus on AddRef and Release:

‘ CHardway (CLSID_CHardway)
Implements IID_IHardway ‘ Every class implements default interface
Implements IID_IUnknown ‘ Every interface implements IUnknown
‘ Any class can implement additional interfaces
§

’ Private variables
Private c As Long ‘ Internal reference count

Function IUnknown_QueryInterface(iid As GUID) As Object
§

Sub IUnknown_AddRef()
c = c + 1
End Sub

Sub IUnknown_Release()
c = c - 1
If c = 0 Then
RaiseEvent Me.Class_Terminate
Erase Me
End If
End Sub

’ The rest of the class
§

This code is speculative because there isn’t really a B-- to write it with. In particular, the Erase Me statement in Release is based on the speculation that the object was originally allocated with ReDim.