Stingray® Foundation : Chapter 3 Interface‑Based Programming : Reference Counting
Reference Counting
Reference counting is another service that is useful in interface-based programming. COM requires that all interfaces are reference counted, but for our C++ interfaces reference counting is optional. The interface IRefCount defines the AddRef() and Release() methods needed to perform reference counting. The signatures of AddRef() and Release() in IRefCount are identical to the signatures in IUnknown, which makes it possible to mix IRefCount into classes that implement IUnknown so they can share the same reference counting implementation. In other words, IRefCount integrates seamlessly with IUnknown. Accordingly, smart pointer classes written to work with IUnknown, such as ATL’s CComPtr, work for IRefCount-based classes.
SFL provides a default implementation of IRefCount that you can mix into a concrete class. The CRefCountImpl is a template class that takes the base class as a template parameter and implements reference counting. Remember that the implementation of reference counting provided by CRefCountImpl is not thread-safe — it does not use the InterlockedIncrement() and InterlockedDecrement() functions.
NOTE >> If your classes need to be thread safe, do not use CRefCountImpl.
Example 6 modifies our cow so that it supports reference counting.
Example 6 – Adding support for reference counting
class IAnimal : public IQueryGuid, public IRefCount
{
public:
virtual void Eat() = 0;
virtual void Sleep() = 0;
virtual void Reproduce() = 0;
};
 
class IFood : public IQueryGuid, public IRefCount
{
public:
virtual void BeConsumed() = 0;
};
 
class CCow : public CRefCountImpl<IAnimal>, public IFood
{
public:
BEGIN_GUID_MAP(CCow)
GUID_ENTRY(IAnimal)
GUID_ENTRY2(IQueryGuid, IAnimal)
GUID_ENTRY2(IRefCount, IAnimal)
END_GUID_MAP
};