#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vld.h> // 内存泄漏检测
using namespace std;
class String;
ostream& operator<<(ostream &out, const String &s);
// 引用计数类,通过深拷贝来构造
// 同时提供Increase Decrease来管理引用计数
class StringRep
{
friend class String;
friend ostream& operator<<(ostream &out, const String &s);
public:
StringRep(const char *s = ""):useCount(0)
{
if (s == NULL)
{
str = new char[1];
str[0] = '\0';
}
else
{
str = new char[strlen(s) + 1];
strcpy(str, s);
}
}
StringRep(const StringRep &s) :useCount(0)
{
str = new char[strlen(s.str) + 1];
strcpy(str, s.str);
}
StringRep& operator=(const StringRep &s)
{
if (this != &s)
{
delete[]str;
str = new char[strlen(s.str) + 1];
strcpy(str, s.str);
}
return *this;
}
void Increase()
{
++useCount;
}
void Decrease()
{
if (--useCount == 0)
// 如果引用计数为0,自杀行为delete会调用析构释放成员str
// 同时释放自身对象StringRep new 出来的空间
delete this;
}
~StringRep()
{
if (str != NULL)
delete[] str;
str = NULL;
}
private:
char *str;
int useCount; // 引用计数
};
// 应用类,通过浅拷贝来构造
// 成员数据位引用计数类对象指针
// 通过引用计数类对象的引用计数实现写时拷贝
class String
{
friend ostream& operator<<(ostream &out, const String &s);
public:
String(const char* str = "")
{
rep = new StringRep(str);
rep->Increase();
}
String(const String &s)
{
rep = s.rep;
rep->Increase();
}
String& operator=(const String &s)
{
if (this != &s)
{
rep->Decrease();
rep = s.rep;
rep->Increase();
}
return *this;
}
// 写时拷贝方法的实现,即有写的操作时实现深拷贝
char& operator[](int pos)
{
// 引用计数大于1,有多个对象共享空间
if (rep->useCount > 1)
{
// 申请新的空间
StringRep *newRep = new StringRep(rep->str);
// 引用计数减少
rep->Decrease();
// 指向新的空间
rep = newRep;
// 新空间的引用计数增加
rep->Increase();
}
return rep->str[pos];
}
~String()
{
rep->Decrease();
}
private:
StringRep *rep; // 引用计数类指针,通过引用计数类来管理数据成员
};
// 重载输出运算符
ostream& operator<<(ostream &out, const String &s)
{
out << s.rep->str;
return out;
}
int main()
{
// s1 s2 s3 共享空间
String s1("hello");
String s2 = s1;
String s3;
s3 = s1;
// 重载[]运算符,有写的操作,实现写时拷贝,即深拷贝
s2[0] = 'H';
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
system("pause");
return 0;
}
c++ 写实拷贝实现demo
最新推荐文章于 2022-06-14 17:08:26 发布