OOPortal OOPortal


Basic COM  «Prev  Next»
Lesson 12 IUnknown reference counting
Objective Understand lifetime management with AddRef and Release.
Now that we've discussed interface navigation with IUnknown::QueryInterface, the next step is to look at lifetime management with AddRef and Release.

Lifetime of a COM object

COM provides automatic invocation of a COM server via its runtime support and the system's service control manager (SCM) when a client requests access to a COM object in the server. The key point here is that COM automatically starts the server. Ideally, we would also like COM to terminate execution of the server when its COM objects are no longer being used.
COM uses a reference-counting scheme to manage the lifetime of COM object. COM objects increment a reference count whenever they give away (assign) an interface pointer to a client in QueryInterface. COM clients (indirectly) decrement the reference count when they no longer need access to the interface. Methods AddRef and Release in IUnknown support incrementing and decrementing reference counts.
The conventional reference-counting implementation uses a member variable as a counter. QueryInterface calls AddRef, after a successful assignment of an interface pointer, to increment the counter. The client calls Release when it is finished using an interface pointer; Release decrements the reference counter.
The following code extends CMyComObject:

class CMyComObject : public IMyComInterface,
  public IYourComInterface 
{
   ULONG m_refcnt;

... Same as previous definitions ,,,

   CMyComObject() : m_refcnt(0) { ; }
};


Notice member variable m_refcnt has been added. m_refcnt is initialized to 0 in the initializer list of the class constructor.
The following is the implementation of QueryInterface, AddRef, and Release.
AddRef, called from QueryInterface, increments m_refcnt
iunknown reference counting
Many COM implementations delete an object when it is no longer in use.