引用计数

来源:互联网 发布:js责任链模式 编辑:程序博客网 时间:2024/06/05 15:57
#include<iostream>
using namespace std;
class String
{
public:
String(const char* str)
:_str(new char[strlen(str)+1])
{
strcpy(_str,str);
_refcount = new int(1);
}
~String()
{
if(--_refcount[0] == 0 && _str != NULL)
{
delete []_refcount;
delete[] _str;
}
}

String(const String& s)
:_str(s._str)
,_refcount(s._refcount)
{
++_refcount[0];
}

String& operator=(const String& s)
{
if(this != &s)
{
_str = s._str;
_refcount = s._refcount;
++_refcount[0];
}
return *this;
}
public:
char* _str;
int* _refcount;//引用计数
};
int main()
{
String s1("abcd");
String s2(s1);
String s3 = s1;
s3 = s2;
return 0;
}
0 0