Basic COM  «Prev  Next»
Lesson 12 IUnknown reference counting
Objective Understand lifetime management with AddRef and Release.

IUnknown Reference Counting

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 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.

  1. AddRef, called from QueryInterface, increments m_refcnt
  2. Release decrements m_refcnt. If its value goes to 0, Release deletes the instance of CMyComObject and returns 0. A reference count of 0 indicates that the COM object and its interfaces are no longer in use.
iunknown reference counting
Many COM implementations delete an object when it is no longer in use.

Who creates and destroys a COM Object?

In the Release code in the lesson, a call to delete is made when the reference count goes to 0. The COM object actually deletes itself. But who creates it? Who calls the new CMyComObject?
One thing to keep in mind is that this is COM, not C++. The client does not call new to create a COM object. Instead, the client calls COM API functions to get an interface pointer to a class factory. The client asks the class factory to create an instance of the COM object it knows how to create. In response, the class factory code within the server creates a new C++ class that implements the COM object.