C++ Linked Lists   «Prev  Next»
Lesson 11A string class using reference counting
ObjectiveExamine the use of reference semantics for copying in a string class.

C++ String Class and Reference counting

How are reference semantics used for copying in a string class.
This string class has shallow copy semantics because pointer assignment replaces copying. In shallow copy semantics, a new value is not created. Instead, a pointer variable is assigned the address of the existing value. We use the class str_obj to create actual object values:
//Reference counted strings
#include  <string.h>
#include  <iostream.h>

class str_obj {
public:
   int    len, ref_cnt;
   char*  s;
   str_obj() : len(0), ref_cnt(1)
      { s = new char[1]; s[0] = 0; }
   str_obj(const char* p) : ref_cnt(1)
      { len = strlen(p); s = new char[len + 1];
        strcpy(s, p); }
   ~str_obj() { delete []s; }
};

The publicly used class my_string handles the str_obj instances and is called a handler class.


class my_string {
public:
   my_string() { st = new str_obj; }
   my_string(const char* p) {st = new str_obj(p);}
   my_string(const my_string& str)
      { st = str.st; st -> ref_cnt++; }
   ~my_string();
   void  assign(const my_string& str);
   void  print() const { cout << st -> s; }
private:
   str_obj*  st;
};

The str_obj declares string objects that are used by my_string. Notice how the str_obj class is basically used for construction and destruction of objects using free store. Upon construction of a str_obj, the ref_cnt variable is initialized to 1 The techniques illustrated are common ones for this type of aggregate. Now let's take a closer look at how these two classes work together.


Common Techniques

  1. The type str_obj is required implementation detail for my_string.
  2. The detail could not be directly placed in my_string without destroying the potential many-one relationship between objects of type my_string and referenced values of type str_obj.
  3. The values of my_string are in the class str_obj, which is an auxiliary class for its use only.

SEMrush Software