Using RWTCountedPointer
RWTCountedPointer is a smart pointer template class that acts as a handle to a reference-counting body. Each time an instance of this class is bound to a body instance, it increments the reference-count maintained by that body. Each time an instance of this class detaches from a body instance, it decrements the body's reference-count and, if there are no more references, deletes the body instance. The reference-counting relieves clients of the burden of tracking whether it is safe to delete a body instance.
The class specified as the
Body parameter to
RWTCountedPointer must provide:
• A member function for incrementing the reference-count, declared as void addReference()
• A member function for decrementing the reference-count, declared as unsigned removeReference()
The Body has the responsibility to maintain the reference-count, usually by containing an attribute member of type unsigned.
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.