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.