C++ Linked Lists   «Prev  Next»
Lesson 12Using reference counting
ObjectiveImprove the reference counting form of the my_string class.

Using reference counting

The client will use objects of type my_string. These objects are implemented as pointers st to values of type str_obj. Notice the copy constructor for this class and how it uses reference semantics to produce a copy.
The semantics of assign() show some of the subtleties of using reference counting:
void my_string::assign(const my_string& str)
{
   if (str.st != st) {
      if (--st -> ref_cnt == 0)
         delete st;
      st = str.st;
      st -> ref_cnt++;
   }
}

The assignment occurs if the string is not being assigned its same value. The assignment causes the assigned variable to lose its previous value. This is equivalent to decrementing the reference count of the pointed at str_obj value. Whenever an object's reference count is decremented, it gets tested for deletion. The advantage of this over normal copying is clear. A very large aggregate is copied by reference using a few operations. There is a small amount of additional storage for the reference counter. Also, each possible change to a pointer adds a reference count operation. The destructor must also test the reference count before actual deletion.
my_string:: ~my_string()
{
   if (--st -> ref_cnt == 0)
      delete st;
}

Singly Linked List - Exercise

Click the Exercise link below to improve the reference counted form of the my_string class.
Singly Linked List - Exercise