您的位置:首页 > 编程语言 > C语言/C++

【C++】引用计数

2016-04-22 13:06 483 查看
#include <iostream>
using namespace std;

class String
{
public:
String(const char* str)
:_str(new char[strlen(str) + 5])
{
_str += 4;
strcpy(_str, str);

_GetRefCount(_str) = 1;
}

String(const String& s)
:_str(s._str)
{
++_GetRefCount(_str);
}

~String()
{
_Release();
}

String& operator=(const String& s)
{
if(_str != s._str)
{
_Release();

_str = s._str;
++_GetRefCount(_str);
}

return *this;
}
private:
int& _GetRefCount(char* _ptr)//引用计数
{
return *((int*)(_ptr - 4));
}

void _Release()//释放内存
{
if(--_GetRefCount(_str) == 0)
{
delete[] (_str - 4);
}
}
private:
char* _str;
};

void Test1()
{
String s1("aaaaaa");
String s2(s1);
}
void Test2()
{
String s1("aaaaaa");
String s2(s1);
String s3("bbbbbbbb");
s1 = s3;
}
int main()
{
//Test1();
Test2();
return 0;
}

Test1:s2._str指向s1._str, s2的引用计数变为2



Test2:s1._str指向s3._str, s2的引用计数变为1



s3的引用计数变为2

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: