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
Now another Foo instance and two new pointers are created.
FooPointer p3(new Foo); //6
FooPointer p4 = p3; //7
p4->bar();
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;
}
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.