Platform SDK: MAPI

Implementing the IUnknown Interface

The methods of the IUnknown interface, implemented in every MAPI object, support interobject communication and object management. IUnknown has three methods: QueryInterface, AddRef, and Release. QueryInterface enables one object to determine if another object supports a particular interface. With QueryInterface, two objects with no prior knowledge of each other's functionality can interact. If the object implementing QueryInterface does support the interface in question, it returns a pointer to the implementation of the interface. If the object does not support the requested interface, it returns the MAPI_E_INTERFACE_NOT_SUPPORTED value.

When QueryInterface returns a requested interface pointer, it must also increase what is known as the new object's reference count. An object's reference count is a numeric value used to manage the object's lifespan. When the reference count is greater than one, the object's memory cannot be freed because it is actively being used. It is only when the reference count drops to zero that the object can be released safely.

The other two IUnknown methods, AddRef and Release, manage the reference count. AddRef increments the reference count while Release decrements it. All methods or API functions that return interface pointers, such as QueryInterface, must call AddRef to increment the reference count. All implementations of methods that receive interface pointers must call Release to decrement the count when the pointer is no longer needed. Release checks for an existing reference count, freeing the memory associated with the interface only if the count is 0.

Note  Because AddRef and Release are not required to return accurate values, callers of these methods must not use the return values to determine if an object is still valid or has been destroyed.