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

【c++】引用计数

2015-06-05 19:24 537 查看
#include <iostream>
#include <string.h>
using namespace std;

class String;

// 封装一个计数器的类来维护,可以隐藏起来,即用户不必关心是如何实现的
class String_Rep
{
friend class String;
public:
String_Rep(const char *str = " ") :count(0)
{
m_data = new char[strlen(str) + 1];
strcpy(m_data, str);
}
~String_Rep()
{
delete[]m_data;
}
public:
void increment()
{
count++;
}
void decrement()
{
if (--count == 0)
{
delete this;// 哪一个rep的count为0了释放当时的rep
}
}
private:
char *m_data;
int count;
};

//////////////////////////////////////////////////////////////////////

class String
{
public:
String(const char *str = " ") :rep(new String_Rep(str))
{
rep->increment();
}
String(const String &s) :rep(s.rep)
{
rep->increment();
}
String& operator=(const String &s)
{
if (this != &s)
{
rep->decrement();// 迭代器
rep = s.rep;
rep->increment();
}
return *this;
}
~String()
{
rep->decrement();
}
public:
void print()const
{
cout << rep->m_data << endl;
}
private:
String_Rep *rep;// 句柄
};

int main()
{
String s1("hello");
String s2;
s2 = s1;
String s3("world");
String s4;
s4 = s3;
s1.print();
s2.print();
s3.print();
s4.print();
return 0;
}


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