#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
#include<string.h>
#include<windows.h>
#if 0
class String
{
public:
String(const char* str = "")
:_str(new char[strlen(str) + 1])
,_retCount(new int(1))
{
strcpy(_str, str);
}
String(const String& s)
:_str(s._str)
,_retCount(s._retCount)
{
_retCount[0]++;
}
String& operator=(const String& s)
{
if (this != &s)
{
if (--_retCount[0] == 0)
{
delete[] _str;
delete[] _retCount;
}
_str = s._str;
_retCount = s._retCount;
++_retCount[0];
}
return *this;
}
~String()
{
if (--_retCount[0] == 0)
{
delete[] _str;
delete[] _retCount;
}
}
private:
char* _str;
int* _retCount;
};
#endif
//上面是是每个对象对应一个整型空间(即_refCount)存放指向这块空间的对象个数
//优化:不引用_refCount,但每次给_str开辟空间的时候,多开辟四个字节,用来记录指向此空间的对象个数,
//规定用开头那四个字节来计数。
class String
{
public:
String(const char* str = "")
:_str(new char[strlen(str) + 1 + 4])
{
cout << "String()" << endl;
_str += 4;
strcpy(_str, str);
GetCount() = 1;
}
String(String& s)
:_str(s._str)
{
cout << "String(String& s)" << endl;
GetCount()++;
}
String& operator=(String& s)
{
cout << "String& operator=" << endl;
if (this != &s)
{
Release();
_str = s._str;
GetCount()++;
}
return *this;
}
~String()
{
cout << "~String()" << endl;
Release();
}
char& operator[](size_t index)
{
if (GetCount() == 1) //如果计数器为1 则直接返回
return _str[index];
GetCount()--;
char* tmp = _str;
_str = new char[strlen(tmp) + 1 + 4];
_str += 4;
strcpy(_str, tmp);
GetCount() = 1;
return _str[index];
}
private:
int& GetCount()
{
return *(int*)(_str - 4);
}
void Release()
{
if (--GetCount() == 0)
{
cout << "释放" << endl;
delete[](_str - 4);
_str = NULL;
}
}
private:
char* _str;
};
int main()
{
String s1 = "hello world";
String s2 = s1;
cout << s1[3] << s2[4] << endl;
/*
int begin = (int)GetTickCount64();
for (int i = 0; i < 1000; i++)
{
String s2 = s1;
}
int end = (int)GetTickCount64();
cout << "run time:" << end - begin << endl;
*/
return 0;
}
写时拷贝
最新推荐文章于 2020-10-08 14:34:38 发布