Releasing the Object

The final operation required in a COM client when dealing with an object from some other server is to free that object when the client no longer needs it. This is achieved by calling the Release member function of all interfaces obtained during the course of using the object.

Recall that a function that creates or synthesizes a new interface pointer is responsible for calling AddRef through that pointer before returning it to the caller of the function. This applies to the IClassFactory::CreateInstance function as well as CoCreateInstance (and for that matter, CoGetClassObject, too, which is why you must call IClassFactory::Release after creating the object). Therefore, as far as the client is concerned, the object will have a reference count of one after creation. The object may, in fact, have a higher reference count if it is also being used from other clients as well, but each client is only responsible and cognizant of the reference counts added on its behalf.

The other primary function that creates new interface pointers is QueryInterface. Every call the client makes to QueryInterface to obtain another interface pointer will internally generate another call to AddRef in that object, incrementing the reference count. Therefore, in addition to calling Release through the interface pointer obtained in the creation sequence, the client must also call Release through any interface pointer obtained from QueryInterface (this is illustrated in the pseudo-code of the previous section).

The bottom line is that the client is responsible for matching any operation that generates a call to AddRef through a given interface pointer with a call to Release through that same interface pointer. It is not necessary to call Release in the opposite order of calls to AddRef; it is just necessary to match the pairs. Failure to do so will cause memory leaks as objects are not freed and servers are not allowed to shut down properly. This is no different that forgetting to free memory obtained through malloc.

Finally, although the client matches its calls to AddRef and Release, the actual object may still continue to run and the server may continue to execute as well without any objects in service. The object will continue if other clients are using that same object and thus have reference counts on it. Only when all clients have released their references will that object free itself. The server will, of course, continue to execute as long as there is an object to serve, but the client does have some power over keeping a server running even without objects. That is the purpose of Server Management functions in COM.