您好,登錄后才能下訂單哦!
#include<iostream> using namespace std; class String { public: /*String(const char* str=" ") :_str(new char[strlen(str)+1]) { strcpy(_str, str); } */ String(const char* str = " ") { if (str == NULL) { _str = new char; _str[0] = '\0'; } else { _str = new char[strlen(str) + 1]; strcpy(_str, str); } } /*String(const String& other) :_str(NULL) { _str = new char[strlen(other._str) + 1]; strcpy(_str, other._str); }*/ String(const String& other) :_str(NULL) { String tmp(other._str);//創(chuàng)建一個臨時對象 swap(_str, tmp._str); } String& operator=(String& other) { if (this != &other) { delete[] _str; _str = new char[strlen(other._str) + 1]; strcpy(_str, other._str); } return *this;//返回值支持鏈?zhǔn)奖磉_(dá)式 } char *GetStr() { return _str; } char& operator[](size_t index)//若不用引用,再它返回時會返回一個匿名對象為一個常量不可改變 { return _str[index]; } /*String& operator=(String other) { swap(_str, other._str);//現(xiàn)代寫法即傳過來一個臨時對象 return *this; }*/ ~String() { if (_str) delete[] _str; } protected: char *_str; }; void Test() { char* ptr = "abcd"; String s1(ptr); String s2(s1); String s3("def"); s3 = s2; //s1[0] = 'x'; cout<<s3.GetStr() << endl; }
若只定義一個全局的整型變量,它只適用于指向同一個內(nèi)存塊。
用引用計數(shù)解決淺拷貝后多次析構(gòu)崩潰問題(寫時拷貝),每塊空間都有各自的指針指向。
#include<iostream> using namespace std;
class String { public: String(const char* str = " ") :_str(new char[strlen(str) + 5]) { *((int*)_str) = 1; //多開4字節(jié)空間保存有幾個指針指向該塊空間 _str += 4; strcpy(_str, str); } /*String(const char* str = " ") { if (str == NULL) { _str = new char; _str[0] = '\0'; } else { _str = new char[strlen(str) + 1]; strcpy(_str, str); } }*/ String(const String& other) :_str(other._str) { ++*(((int*)_str)-1); } //String(const String& other) //:_str(NULL) //{ //String tmp(other._str);//創(chuàng)建一個臨時對象 //swap(_str, tmp._str); //} String& operator=(String& other) { if (this != &other) { if (--*(((int*)_str) - 1) == 0) { //若只有一個指針指向該空間則釋放掉它,讓其重新指向另一塊空間 _str -= 4;//釋放空間時一定從頭釋放 delete[] _str; } } _str = other._str; ++*(((int*)(other._str))-1); return *this;//返回值支持鏈?zhǔn)奖磉_(dá)式 } char *GetStr() { return _str; } char& operator[](size_t index)//若不用引用,再它返回時會返回一個匿名對象為一個常量不可改變 { return _str[index]; } /*String& operator=(String other) { swap(_str, other._str);//現(xiàn)代寫法即傳過來一個臨時對象 return *this; }*/ ~String() { if (_str) { if (--*(((int*)_str) - 1) == 0) { _str -= 4; //釋放空間時一定從頭釋放 delete[] _str; } } } protected: char *_str; }; void Test() { char* ptr = "abcd"; String s1(ptr); String s2(s1); String s3("def"); s3 = s2; //s1[0] = 'x'; cout << s3.GetStr() << endl; }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。