Deriving from RWTCountingBody for Reference Counting
An easy way to provide these requirements is to derive the body class from the RWTCountingBody helper class.
Example 64 shows the use of RWTCountedPointer with a template parameter of class Foo, which is derived from RWTCountingBody. See buildspace\examples\pointer\RWTCountedPointerEx.cpp for the full example.
RWTCountingBody is templatized on a mutex type in order to implement the RWTMonitor interface.
Example 64 – Providing reference counting for a counted pointer
class Foo : public RWTCountingBody<RWMutexLock> //1
{
public:
Foo() { cout << "I'm a foo instance. My address is " << this
<< endl; }
~Foo() { cout << "I'm dying ! My address is " << this << endl; }
void bar(void) { cout << "I like this place: " << this << endl; }
};
 
typedef RWTCountedPointer<Foo> FooPointer;
 
int main() {
try {
FooPointer p1(new Foo); //2
{ // begin new scope
FooPointer p2 = p1; //3
p2->bar(); //4
} // end new scope //5
//1 Foo inherits from the RWTCountingBody<RWMutexLock> helper class to gain multithread–safe reference-counting.
//2 p1 points to an unnamed Foo instance on the heap.
//3 In a new scope, p2 is created to point to the same unnamed Foo instance as p1. This copy construction increments the reference-counter maintained inside Foo. Figure 39 shows the pointers at this stage in the processing.
Figure 39 – Creating a pointer by copy construction
//4 bar() is called for the unnamed instance stored in the heap. The displayed address is the same as when p1 was created.
//5 When p2 goes out of scope and is destroyed, the reference-counter inside Foo is decremented.
Now another Foo instance and two new pointers are created.
 
FooPointer p3(new Foo); //6
FooPointer p4 = p3; //7
p4->bar();
//6 p3 points to a new Foo instance on the heap.
//7 p4 is created to point to the same Foo instance as p3. Figure 40 shows the pointers at this stage in the processing. Notice that p2 no longer exists.
Figure 40 – Pointers during the swapWith operation
The swapWith() operation causes two of the pointers to trade bodies.
 
p4.swapWith(p1); //8
p4->bar();
}
catch(RWxmsg& msg) {
cout << msg.why() << endl;
}
return 0;
}
 
//8 After the swapWith() operation, p4 points to the Foo originally identified by p1, and p1 points to the Foo originally identified by p3. Figure 41 shows the pointers now.
Figure 41 – Pointers after the swapWith operation
RWTCountedPointer is type-intrusive; your class must implement the reference-counter or inherit from RWTCountingBody. The advantage is that by implementing the reference counter you gain efficiency and have more control over the counter’s behavior. If you need a class that is equivalent to RWTCountedPointer but is not type-intrusive, you can use the RWTCountingPointer class.