10. Reference pointers

AGX use a reference pointer system for all objects allocated on the heap. Reference pointers are a special kind of pointer that can only point to objects derived from agx::Referenced. A Referenced object keeps track of the number of reference pointers pointing to it. Whenever an instantiated class derived from Reference discovers that the number of referencing points is zero, it will automatically be de-allocated.

There are two types of reference pointers in AGX, ref_ptr and observer_ptr. ref_ptr is a strong pointer, which will during its lifetime keep the referenced object from being deleted. An observer_ptr on the other hand, will be notified when the referenced object is de-allocated. ref_ptr and observer_ptr both has a method isValid() that return false if it is pointing to a deallocated object. The type-cast operator is overloaded, so a ref_ptr<A> and observer_ptr<A> can be used anywhere in the code, as if it was of type A *. Example:

struct A : public agx::Referenced
{
};
agx::ref_ptr<A> a;
A* aPtr = a; // Ok, as the reference pointer will be cast to a A*

There are a few pitfalls when using reference pointers, an example:

// Problem #1: Local ref_ptr going out of scope
A* createA()
{
agx::ref_ptr<A> aRef = new A;

// When this function returns, aRef will go out if scope and the
// memory be deallocated. The number of reference pointers pointing to
// this object is decremented to zero, and it will be deallocated.
// So we are returning an invalid object!
return aRef;
}

In the above example one should either change the return type of the function to return an agx::ref_ptr<A>, or avoid using a ref_ptr inside the function. The latter solution will however be a potential memory leak, because memory will not be freed if an exception is thrown inside createA().