STXXL  1.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Reference Counted (Shared) Objects

Some objects in STXXL are reference counted. This is usually done for large objects, which should not be copied deeply in assignments. Instead, a reference counting pointer is used, which holds a handle while the pointer exists and deletes the object once all pointers go out of scope. Examples are matrices and stream::sorted_runs.

The method used is called counting_ptr or intrusive reference counting. This is similar, but not identical to boost or TR1's shared_ptr.

The counting_ptr is accompanied by counted_object, which contains the actual reference counter (a single integer). A reference counted object must derive from counted_object :

struct something : public stxxl::counted_object
{
};

Code that now wishes to use pointers referencing this object, will typedef an counting_ptr, which is used to increment and decrement the included reference counter automatically.

typedef stxxl::counting_ptr<something> something_ptr
{
// create new instance of something
something_ptr p1 = new something;
{
// create a new reference to the same instance (no deep copy!)
something_ptr p2 = p1;
// this block end will decrement the reference count, but not delete the object
}
// this block end will delete the object
}

The counting_ptr can generally be used like a usual pointer or shared_ptr (see the docs for more).

There is also const_counting_ptr to return const objects (note that a const counting_ptr will only render the pointer const, not the enclosed object).