String類的寫時拷貝實例
更新時間:2017年01月18日 10:33:21 投稿:jingxian
下面小編就為大家?guī)硪黄猄tring類的寫時拷貝實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
實例如下:
#include<iostream>
using namespace std;
class String;
ostream& operator<<(ostream &out, const String&s);
//引用計數(shù)器類
class String_rep
{
friend class String;
friend ostream& operator<<(ostream &out, const String&s);
public:
String_rep(const char *str )
:use_count(0)
{
if (str == NULL)
{
data = new char[1];
data[0] = '\0';
}
else
{
data = new char[strlen(str) + 1];
strcpy(data, str);
}
}
String_rep(const String_rep &rep) :use_count(0)
{
data = new char[strlen(rep.data) + 1];
strcpy(data, rep.data);
}
String_rep& operator=(const String_rep &rep)
{
if (this != &rep)
{
delete[]data;
data = new char[strlen(rep.data) + 1];
strcpy(data, rep.data);
}
return *this;
}
~String_rep()
{
delete[]data;
data = NULL;
}
public:
void increase()
{
++use_count;
}
void decrease()
{
if (use_count == 0)
{
delete this; //自殺行為 釋放this所指的空間,在釋放之前調(diào)動這個類的析構(gòu)函數(shù)
}
}
private:
char *data;
int use_count;
};
////////////////////////////////////////////////////////////////////////////////////////
class String
{
friend ostream& operator<<(ostream &out, const String&s);
public:
String(const char* str = " ")
{
rep = new String_rep(str);
rep->increase();
}
String(const String &s)
{
rep = s.rep; //淺拷貝
rep->increase();
}
String& operator=(const String &s)
{
if (this != &s)
{
rep->decrease(); //模擬delete
rep = s.rep; //模擬new
rep->increase(); //模擬strcpy
/*rep = s.rep; //這會更改引用計數(shù)器指針 ,造成s內(nèi)存泄漏
rep->increase();*/
}
return *this;
}
~String()
{
rep->decrease();
}
public:
void to_upper()
{
if (rep->use_count > 1)
{
String_rep* new_rep = new String_rep(rep->data);
rep->decrease();
rep = new_rep;
rep->increase();
}
char* ch = rep->data;
while (*ch != '\0')
{
*ch -= 32;
++ch;
}
}
private:
String_rep *rep; //引用計數(shù)器
};
ostream& operator<<(ostream &out, const String&s)
{
out << s.rep->data;
return out;
}
void main()
{
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;
}
以上這篇String類的寫時拷貝實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C語言使用realloc函數(shù)實現(xiàn)通訊錄源碼分析
什么是動態(tài)通訊錄,就是在靜態(tài)的基礎(chǔ)上改進(jìn)了一下,不在使用數(shù)組,而是使用指針和動態(tài)內(nèi)存開辟的函數(shù),當(dāng)空間不夠的時候,便進(jìn)行增容2023-02-02
C語言編程技巧 關(guān)于const和#define的區(qū)別心得
盡量用const和inline而不用#define 這個條款最好稱為:“盡量用編譯器而不用預(yù)處理”,因為#define經(jīng)常被認(rèn)為好象不是語言本身的一部分。這是問題之一。再看下面的語句:2013-02-02

