I have tried to implement a copy on write string class with value semantics and reference counting.
I wanted to support indexing, so I have overloaded the operator[] and to differentiate between the l-value and r-value usage it is returning a proxy object.
#include <iostream>
#include <string.h>
class proxy;
//Reference counting class.Also holds the string.
class RC
{
public:
RC(const char * str);
~RC();
private:
char* str;
int count;
friend class mystring;
friend class proxy;
};
class mystring
{
public:
mystring(const char* str);
mystring& operator=(const mystring& str);
mystring(const mystring& str);
~mystring();
void print() const;
proxy operator[](int n);
private:
RC *pRC;
friend class proxy;
};
class proxy
{
public:
proxy(mystring* r,int n);
proxy& operator=(const char& c);
proxy& operator=(const proxy& c);
operator char() const;
private:
int n;
mystring* ptr;
};
RC::RC(const char * str1)
:str(new char[strlen(str1)+1]),count(1)
{
strcpy(str,str1);
}
RC::~RC()
{
if(--count == 0)
delete [] str;
}
proxy mystring::operator[](int n)
{
return proxy(this,n);
}
mystring::mystring(const char* str)
:pRC(new RC(str))
{
}
mystring& mystring::operator=(const mystring& rhs)
{
if(this != &rhs)
{
if(--pRC->count == 0)
delete pRC;
pRC = rhs.pRC;
++pRC->count;
}
return *this;
}
mystring::mystring(const mystring& rhs)
{
pRC = rhs.pRC;
++pRC->count;
}
mystring::~mystring()
{
if(--pRC->count == 0)
delete pRC;
}
void mystring::print() const
{
std::cout << pRC->str << ":" << pRC->count << '\n';
}
proxy::operator char() const
{
return ptr->pRC->str[n];
}
proxy::proxy(mystring* r,int n)
:ptr(r),n(n)
{}
proxy& proxy::operator=(const char& c)
{
if(c != ptr->pRC->str[n])
{
char cpy[strlen(ptr->pRC->str)+1];
strcpy(cpy,ptr->pRC->str);
ptr->pRC->~RC();
cpy[n] = c;
ptr->pRC = new RC(cpy);
}
return *this;
}
proxy& proxy::operator=(const proxy& rhs)
{
if(this != &rhs)
{
*this = (char)rhs;
}
return *this;
}
Can you please help me improve the code?