<pre name="code" class="cpp">深拷贝和浅拷贝各有好处,但是在浅拷贝时往往会出现对指向同一片内存空间的指针变量的多次释放,在字符串类中封装一个引用计数类对象指针(句柄),通过引用计数器使指向同一片内存空间的指针仅被delete一次
#include<iostream>
#include<string>
using namespace std;
class String;
class String_rep
{
friend class String;
public:
String_rep(const char *str=""):use_count(0)
{
m_data = new char[strlen(str)+1];
strcpy(m_data,str);
}
~String_rep()
{
delete []m_data;
}
public:
void increment()
{use_count++;}
void decrement()
{
if(--use_count == 0)
{
delete this;
}
}
private:
char *m_data;
int use_count;
};
class String
{
public:
String(const char *str=""):rep(new String_rep(str))
{
rep->increment();
}
String(const String &s):rep(s.rep)
{
rep->increment();
}
void operator=(const String &s)
{
if(this != &s)
{
rep->decrement(); //-->迭代器 在被赋值之前将自身管理的空间释放
rep = s.rep;
rep->increment();
}
}
~String()
{
rep->decrement(); //对象每析构一次让引用计数器减一,当其值为0时m_data随对象一起析构<pre name="code" class="cpp">
}public:void Print()const{cout<<rep->m_data<<endl;}private: String_rep *rep; //句柄};void main(){String s1("hello");String s2 = s1;String s3 ;
s3= s2;
s1.Print();
s2.Print();
}