Scopira  20080306
Reference counting


The base object class is scopira::tool::object. This is the base class for all classes that want to be:

  • Reference counted via count_ptr
  • Be serializable (streamable to I/O streams)
  • Lifecycle debugging methods

You should almost always inherit from this class virtually. That is:

class myclass : public virtual scopira::tool::object { } ;


Each object descendant, during debug builds exposes an scopira::tool::object::is_alive_object method that returns true if the given object is non-null and valid (not destroyed) and matches an internal magic number. This is useful in catching many bad-memory manipulation errors.

assert(is_alive_object()); // assert that "this" is valid
assert(someobj->is_alive_object()); // assert that someobj is valid

Also while in debug builds, Scopira will notify the user on exit if there are any non-deleted scopira::tool::object decendants in memory. This greatly helps in detecting memory leaks.

Reference counting

Reference counting is the core memory managment style of most Scopira objects in a Scopira application.

All scopira::tool::object decendant instances can be reference counted, but need not be (ie. they can still be created on the stack, etc). However, once an object is reference counted by atleast one counter, that instance now must be reference counted until its destruction. Reference counted objects may be shared by multiple reference counters. When the last counter releases their count, the object is destroyed.

scopira::tool::count_ptr is the basic "smart pointer" template class for handling reference counts. This smart pointer provides all the usual pointer like methods, but makes sure to keep a reference count on the object they contain.

Some sample code:

scopira::tool::count_ptr<someclass> p, p2; // initialized to null by default
p = new p; // create an instance, it is now reference counted
p->somemethods(); // access p
p.get(); // returns a pointer to someclass
*p; // returns a reference to someclass
p2 = p; // two ferences to the same object
p = 0; // won't delete the instance, p2 still has a reference
p2 = 0; // will delete the instance
// note that count_ptr's naturally de-reference count their instance upon their
// destruction. You need not assign null to them explicitly

All scopira::tool::object descendants can be reference counted by scopira::tool::count_ptr by simply proving your own add_ref() and sub_ref() methods. This is typically only done in the most sepecialized of cases, however.

Serializable Objects

To make your own objects serialization, see Object I/O