Skip to content

general_refcounting

shekh edited this page Apr 15, 2018 · 1 revision

VirtualDub Plugin SDK 1.2

Reference counting

Objects in the VirtualDub plugin API are reference counted in order to support shared ownership. Instead of being explicitly destroyed, each object tracks the number of references on it and automatically destroys itself when no references are left.

For those of you familiar with Microsoft COM, the reference counting scheme used here is very similar to that of the COM IUnknown interface.

Creating and destroying references

References to an object are not stored, but are instead virtually counted via the AddRef() and Release() methods. AddRef() adds a reference, whereas Release() removes a reference. For every call to AddRef(), there must be a corresponding call to Release().

Factory methods that return a new object generally have the following prototype:

bool CreateObject(Type **ppObject);

These return true and place a pointer to the new object in *ppObject on success. The new object is returned with one implicit reference that must be removed using Release().

Implementing AddRef and Release

AddRef() and Release()must be implemented in a thread-safe manner, as they may be called on any thread at any time. In Windows, this can be done using the InterlockedIncrement() and InterlockedDecrement() functions, which atomically increment or decrement a 32-bit LONG variable.

Use of the vdxunknown<> template, which is included in the SDK, is highly recommended. When used as a base class, it automatically implements AddRef() and Release() correctly on a specified interface.

When implementing multiple interfaces, all interfaces must share the same reference count. In particular, do not inherit from two base classes that each implement a reference counter without ensuring that only one is used. Inheriting two reference counters is inadvisable for other reasons, but if you must do so, ensure that AddRef() and Release() are consistent across all interfaces supported by an object.

Internal reference counts

It is permissible for objects to internally obtain references on each other. For instance, if your video decoder model uses shared data, you may want to make the shared data reference counted and obtain a reference on it to prevent it from disappearing before the video decoder model. The only caveat to doing this is that a reference loop must never be created, because it will cause objects to leak. For instance, two objects A and B must not keep a permanent reference on each other, as both objects would then have an outstanding reference count of one with no external references.


Copyright (C) 2007-2012 Avery Lee.

Clone this wiki locally