#define _CRT_SECURE_NO_WARNINGS -1
//调用sacnf和strcpy会出现报错
include<iostream>
#include<stdlib.h>
using namespace std;
- 新创建引用计数
代码实现:
class String
{
public:
String(char* str = "") //构造函数
:_str(new char[strlen(str) + 1])
, _pCount(new int(1))
{
strcpy(_str, str);
}
// s2(s1)
String(const String& s)//拷贝构造
:_str(s._str)
,_pCount(s._pCount)
{
(*_pCount)++;
}
void swap(char *x, char*y)
{
char tmp = *x;
*x = *y;
*y = *x;
}
String& operator=(const String& s)
//赋值运算符的重载
{
if (&s != this)
{
//char*str = new char[strlen(str) + 1];
if (--(*_pCount) == 0)
{
delete[] _str;
delete[] _pCount;
_str = NULL;
_pCount = NULL;
}
_str = s._str;
_pCount = s._pCount;
(*_pCount)++;
}
return *this;
}
~String()//析构函数
{
if (--(*_pCount)== 0)
{
delete[]_str;
delete[]_pCount;
_str = NULL;
_pCount = NULL;
}
}
const char* c_str()//返回当前字符串
{
return _str;
}
void CopyOnWrite()//写实拷贝
{
if ((*_pCount) > 1)
{
char* newstr = new char[strlen(_str) + 1];
strcpy(newstr, _str);
(*_pCount)--;
_pCount = new int(1);
}
}
void Insert(size_t pos, const char*str)
{
CopyOnWrite();
}
char& operator[](size_t pos)
{
CopyOnWrite();
return _str[pos];
}
private:
char* _str;
int * _pCount;
};
int main()
{
String s1("123");
String s2(s1);
String s3("456");
s1 = s3;
system("pause");
return 0;
}
- 引用计数在头上:
代码实现:
class String
{
public:
String(char* str = "")
:_str(new char[strlen(str) + 5])
//开辟一个四字节的pCount指针空间
{
strcpy(_str, str);
GetCount() = 1;
}
int& GetCount()
{
return (*(int *)(_str-4));
}
// s2(s1)
String(const String& s)
:_str(s._str)
{
GetCount()++;
}
void swap(char *x, char*y)
{
char tmp = *x;
*x = *y;
*y = *x;
}
String& operator=(const String& s)
{
if (&s != this)
{
//char*str = new char[strlen(str) + 1];
if (--GetCount() == 0)
{
_str -= 4;
delete[] _str;
_str = NULL;
}
_str = s._str;
GetCount()++;
}
return *this;
}
~String()
{
if (GetCount() == 0)
{
_str -= 4;
delete[]_str;
_str= NULL;
}
}
const char* c_str()
{
return (_str-4);
}
void CopyOnWrite()
{
if (GetCount() > 1)
{
char* newstr = new char[strlen(_str) + 5];
newstr += 4;
strcpy(newstr, _str);
GetCount()--;
_str = newstr;
GetCount() = 1;
}
}
void Insert(size_t pos, const char*str)
{
CopyOnWrite();
}
char& operator[](size_t pos)
{
CopyOnWrite();
return _str[pos];
}
private:
char* _str;
};
int main()
{
String s1("123");
String s2(s1);
String s3("456");
s1 = s3;
cout << s3[2] << endl;
s3[2] = 'x';
cout << s3[2] << endl;
system("pause");
return 0;
}