C++中一般实现String类的时候,每次当我们复制String对象的时候,我们会将rep(为String的成员变量)也复制一份。其实我们也可以通过避免这些复制操作来节省一些程序的运行时间,我们的解决方法就是让多个句柄同时指向rep。这样在复制String对象的时候,我们只复制这个句柄而不是rep,这时的句柄变成一个指向用来表示“指向rep的句柄数”的计数器。当指向他的句柄数为0时,我们将删除这个rep。实现如下:
#include <iostream>
using namespace std;
class String{
private:
class String_rep{
public:
int use_count;
char *chars;
String_rep(const char *);
String_rep(const String_rep &);
~String_rep();
void increment();
void decerment();
const String_rep &operator=(const String_rep &);
};
//String_rep* rep;
public:
String_rep* rep;
String(const char * = "");
~String();
String(const String&);
const String &operator=(const String &);
};
String::String_rep::String_rep(const char *cp):use_count(0),chars(new char[strlen(cp) + 1])
{
strcpy(chars, cp);
}
String::String_rep::~String_rep()
{
delete []chars;
}
void String::String_rep::increment()
{
++use_count;
}
void String::String_rep::decerment()
{
if(--use_count == 0)
delete this;
}
String::String_rep::String_rep(const String::String_rep& orig):use_count(0),
chars(new char[strlen(orig.chars) + 1])
{
strcpy(chars,orig.chars);
}
const String::String_rep & String::String_rep::operator=(const String::String_rep& orig)
{
if(this != &orig)
{
delete []chars;
chars = new char[strlen(orig.chars) + 1];
strcpy(chars, orig.chars);
}
return * this;
}
String::String(const char* c):rep(new String_rep(c))
{
rep->increment();
}
String::~String()
{
rep->decerment();
}
String::String(const String & s): rep(s.rep)
{
rep->increment();
}
const String & String::operator=(const String &s)
{
if(rep != s.rep)
{
rep->decerment();
rep = s.rep;
rep->increment();
}
return *this;
}
int main(void)
{
String a("zpw");
String c(a);
cout <<c.rep->use_count<<endl;
String b("yy");
return 0;
}
结果显示:
rep的地址相同的。a和c共同拥有rep。
转载于:https://blog.51cto.com/sanguonaigao/1536918