1 Basics

The C++ backend support for MpsIdl uses a simple reference-counting garbage-collector template class,

 template <class T> class ref;

All reference-counted entities must inherit from

 class Referenceable;

and should implement a virtual destructor.

2 Manipulating references

You can use references almost exactly as if they were pointers to the type they reference:

 ref<MyClass> p = new MyClass(arg1, arg2);

Caveats: if you want the pointer itself, use p.get():

 if (p.get() == someOtherReference.get()) ...

and if you want to downcast, use p.downcast<DerivedType>():

 ref<MyBaseClass> bp = new MyDerivedClass();
   // note - putting a Derived object into a
   // Base pointer - upcasting, in other words
 ref<MyDerivedClass> dp = bp.downcast<MyDerivedClass>();
   // Downcast to extract the concrete Derived
   // from the Base pointer

3 Passing references around

When passing references into subroutines, pass them in as type

 ref<T> const &

because since the calling frame holds a reference to the object, there's no need for the called frame to construct a temporary reference (involving an increment at the start-of-scope and a decrement-and-test at the end-of-scope) for the lifetime of the function.

 void doSomething(ref<MyClass> const &theRef) {

4 Constructing Referenceables

There is one case where you need to take a bit of care: when you're constructing a Referenceable, and then immediately throwing away the pointer you just created. (One example of when it might be convenient to do this is with a Referenceable that, when constructed, might register itself somewhere.)

The only thing to watch out for is that you have to actually put the Referenceable into a ref<X> once in order to increment the reference count above zero, so that when the ref<X> goes away the object is destroyed. So instead of:

  new MyWeirdReferenceable(1, 2, 3);

you need:

  ref<MyWeirdReferenceable> dummy = new MyWeirdReferenceable(1, 2, 3);

Go to Table of Contents

(last modified 23 August 2002 by surazal) Logo