C++ Linked Lists   «Prev  Next»

Modifying C++ Singly linked list - Exercise

Improving Reference counting in my_string

Objective: Improve the reference counted form of the my_string class by asserting in appropriate member functions that ref_cnt is not negative.

The my_string class

This code is also available in a file named my_string.cpp, which can be found in the compressed course download file available on the Resource page.

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;
};

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++;
}
}

my_string:: ~my_string()
{
if (--st -> ref_cnt == 0)
delete st;
}

Paste the source code below and click the Submit button when you are ready to submit this exercise.