LS2Module:Reference counting

From dedicated to promoting white hat, EULA-compliant Inner Space and LavishScript mods
Jump to: navigation, search

Reference counting is a method of 'garbage collection' used by LavishScript 2. This allows objects to be reused, instead of being immediately destroyed in favor of a fresh copy of the same object.

The LavishScript 2 reference counting model assumes 3 things about an object
  1. It starts with a reference count of 1 and will be deleted when that count reaches 0
  2. It has virtual int AddRef() to increment the reference count
  3. It has virtual int Delete() to decrement the reference count (and potentially delete the object and free the memory)

Most LavishScript 2 objects are reference counted with this model.

Example LavishScript 2 Reference Count implementation

Support LS2SmartRef<T> and LS2CodeBoxValue_ObjectRefCountedT<T> for your type T by following this model
class MyClass
      m_RefCount=1; // always assume we have a reference to begin with!

   virtual int AddRef()
      return m_RefCount;

   virtual int Delete()
      if (m_RefCount<=0)
         delete this;
         return 0;
      return m_RefCount;

   int m_RefCount;

Working with reference counted objects

When the API expects to provide you with a reference counted object, it will do so using a T** parameter. When you are finished with your reference to the provided object, you will need to call its Delete() method.

The SDK provides LS2SmartRef<T> to simplify management of reference counted objects by automatically tracking the count of an object. Using a LS2SmartRef also ensures that the reference will be freed in the case of an exception (whereas using your own pointer to the T will require manual exception handling).

LS2SmartRef<T> allows your smart reference to be used as a T*, T**, or T&. Use the -> operator to access members of T (your object), or the . operator to access members of LS2SmartRef (such as to change the reference).

An example of LS2SmartRef usage
// set up a LS2SmartRef to hold an LavishScript2::ILS2CodeBoxType reference
LavishScript2::LS2SmartRef<LavishScript2::ILS2CodeBoxType> pIDisposable;

// call ResolveType, which needs a LavishScript2::ILS2CodeBoxType** in parameter 2
// we will grab a reference to System.IDisposable, and assign it into pIDisposable
LavishScript2::ILS2StandardEnvironment::s_pInstance->ResolveType(L"System.IDisposable",pIDisposable); // LavishScript2::ILS2CodeBoxType**

// say we have another LavishScript2::ILS2CodeBoxType reference called pMyType...
// let's register IDisposable as an interface implemented by pMyType...

// pIDisposable will automatically Clear when it leaves scope
// but for the sake of providing an example using a method from LS2SmartRef...