Reference Counting |
Automatic storage management is not a built-in mechanism in C++, but can be
accomplished through the use of helper classes. Helper<ToolKit> includes a
templatized os_reference
class designed to provide automatic management of
objects in heap memory. It assumes ownership of a heap-allocated object, and
automatically destroys the object when all references to the object are removed.
The following example illustrates
the usefulness of the os_reference class by
creating three references to objects on the heap, and then
changing each reference individually. Notice how the managed object is destroyed
when it is no longer referenced by an os_reference
instance.
#include <iostream>
#include <ospace/helper.h>
class object
{
object( int x = 0 ) : x_(x)
{
cout << "\tconstructing object at " << this
<< " with value " << x_ << endl;
}
~object()
{
cout << "\tdestructing object at " << this
<< " with value " << x_ << endl;
}
int value() const
{
return x_;
}
private:
int x_;
};
typedef os_reference< object > rc;
void
main()
{
cout << "Creating objects" << endl;
rc a1 = new object( 1 );
rc a2 = new object( 2 );
rc a3 = new object( 3 );;
cout << "Change a2 to refer to object #3" << endl;
a2 = a3;
cout << "Change a3 to refer to object #1" << endl;
a3 = a1;
cout << "Change a2 to refer to object #1" << endl;
a2 = a1;
cout << "Exiting" << endl;
}
Creating objects
constructing object at 0x4af10 with value 1
constructing object at 0x4af30 with value 2
constructing object at 0x4af50 with value 3
Change a2 to refer to object #3
destructing object at 0x4af30 with value 2
Change a3 to refer to object #1
Change a2 to refer to object #1
destructing object at 0x4af50 with value 3
Exiting
destructing object at 0x4af10 with value 1
Copyright©1994-2026 Recursion
Software LLC
All Rights Reserved - For use by licensed users only.