#include <stdio.h>
#include <string.h>
class String
{
private:
struct StringValue
{
int refCount;
char *data;
StringValue(const char *initValue);
~StringValue();
};
StringValue *value;
public:
String(const char *initValue = ""); //constructor
String(const String &rhs); //copy constructor
String &operator=(const String &rhs); //assignment operator
const char &operator[](size_t index) const; //重载[]运算符,针对const Strings
char &operator[](size_t index); //重载[]运算符,针对non-const Strings
~String(); //destructor
};
String::StringValue::StringValue(const char *initValue) : refCount(1)
{
data = new char[strlen(initValue) + 1];
strcpy_s(data, 1, initValue);
}
String::StringValue::~StringValue()
{
delete[] data;
}
String::String(const char *initValue) : value(new StringValue(initValue))
{
}
String::String(const String &rhs) : value(rhs.value)
{
++value->refCount;
}
String::~String()
{
if (--value->refCount == 0)
delete value;
}
String &String::operator=(const String &rhs)
{
if (this->value == rhs.value) //自赋值
return *this;
//赋值时左操作数引用计数减1,当变为0时,没有指针指向该内存,销毁
if (--value->refCount == 0)
delete value;
//不必开辟新内存空间,只要让指针指向同一块内存,并把该内存块的引用计数加1
value = rhs.value;
++value->refCount;
return *this;
}
const char &String::operator[](size_t index) const
{
return value->data[index];
}
//重载[]运算符,针对non-const Strings
char &String::operator[](size_t index)
{
if (value->refCount > 1)
{
--value->refCount;
value = new StringValue(value->data);
}
if (index < strlen(value->data))
return value->data[index];
}
#include <iostream>
#include <string>
using namespace std;
std::string a = "lvlv";
void main()
{
char *p = &a[1];
*p = 'a';
std::string b = a;
std::cout << "b:" << b << endl;
system("pause");
return;
}