Memory management: reference counting

SAL3D uses a memory management technique called reference counting for its objects. The idea is that each time an object is copied, only a counter associated with it is incremented and no data is replicated. An object is deleted only when there are no references left pointing to the object.

Implications of reference counting

Altough the use of this reference counting is transparent to the user, it has several implications that should be noted:

Example showing reference counting behaviour

// function to filter a COP object without modifying the original
sal3d::COP getFilteredCOP(const sal3d::COP &cop)
{
    // create a deep copy of the passed COP to avoid modifying the original
    sal3d::COP filteredCOP = cop.copy();
    // do the filtering to filteredCOP
    ...
    return filteredCOP;
}

// function to filter a COP object, this time modifying the original. The
// construction is a bit weird, but just to prove the point
void filterCOP(sal3d::COP cop)
{
    // do the filtering to cop
    ...
}

// we create a COP from a file
sal3d::COP original(filename);
// we get a new COP from the function
sal3d::COP filtered = getFilteredCOP(original);
// here original is still unmodified
filterCOP(original);
// here original will be modified, even though it was passed by value to
// filterCOP