一聚教程网:一个值得你收藏的教程网站

热门教程

String类的写时拷贝实例

时间:2022-06-25 04:40:13 编辑:袖梨 来源:一聚教程网

实例如下:

 代码如下复制代码

#include

usingnamespacestd;

  

classString;

ostream& operator<<(ostream &out,constString&s);

//引用计数器类

classString_rep

{

  friendclassString;

  friendostream& operator<<(ostream &out,constString&s);

 

public:

 代码如下复制代码

   String_rep(constchar*str )

      :use_count(0)

    {

      if(str == NULL)

      {

        data =newchar[1];

        data[0] =''

      }

      else

      {

        data =newchar[strlen(str) + 1];

        strcpy(data, str);

      }

    }

   

    String_rep(constString_rep &rep) :use_count(0)

    {

      data =newchar[strlen(rep.data) + 1];

      strcpy(data, rep.data);

    }

    String_rep& operator=(constString_rep &rep)

    {

      if(this!= &rep)

      {

        delete[]data;

        data =newchar[strlen(rep.data) + 1];

        strcpy(data, rep.data);

      }

      return*this;

    }

    ~String_rep()

    {

        delete[]data;

        data = NULL;

    }

public:

 代码如下复制代码

  voidincrease()

  {

    ++use_count;

  }

   

  voiddecrease()

  {

    if(use_count == 0)

    {

      deletethis;//自杀行为  释放this所指的空间,在释放之前调动这个类的析构函数

    }

  }

private:

 代码如下复制代码

    char*data;

    intuse_count;

};

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

classString

{

   friendostream& operator<<(ostream &out,constString&s);

public:

  String(constchar* str =" ")

  {

    rep =newString_rep(str);

    rep->increase();

  }

  String(constString &s)

  {

    rep = s.rep;  //浅拷贝

    rep->increase();

  }

  String& operator=(constString &s)

  {

    if(this!= &s)

    {

      rep->decrease(); //模拟delete

      rep = s.rep;     //模拟new

      rep->increase();  //模拟strcpy

      /*rep = s.rep;  //这会更改引用计数器指针 ,造成s内存泄漏

      rep->increase();*/

    }

    return*this;

  }

    ~String()

    {

      rep->decrease();

    }

 

public:

 

 代码如下复制代码

  voidto_upper()

  {

    if(rep->use_count > 1)

    {

      String_rep* new_rep =newString_rep(rep->data);

      rep->decrease();

      rep = new_rep;

      rep->increase();

    }

    char* ch = rep->data;

    while(*ch !='')

    {

      *ch -= 32;

      ++ch;

    }

  }

 

private:

 

 

 代码如下复制代码

  String_rep *rep;//引用计数器

};

 

ostream& operator<<(ostream &out,constString&s)

{

  out << s.rep->data;

  returnout;

}

voidmain()

{

  String s1("hello");

  String s2(s1);

  String s3;

  s3 = s2;

  cout <<"s1="<< s1 << endl;

  cout <<"s2="<< s2 << endl;

  cout <<"s3="<< s3 << endl;

 

   s2.to_upper();

 

  cout <<"-----------------------------------------------"<< endl;

   

  cout <<"s1="<< s1 << endl;

  cout <<"s2="<< s2 << endl;

  cout <<"s3="<< s3 << endl;

}

 

热门栏目