字符串是我們?cè)诰帉?xiě)程序的時(shí)候經(jīng)常用的到的。C++庫(kù)已經(jīng)幫我們實(shí)現(xiàn)了一個(gè)功能更加強(qiáng)大的字符串類string,我們要去了解它是怎么實(shí)現(xiàn)的。
只要是涉及到 string類的地方多少都會(huì)涉及到深淺拷貝的問(wèn)題。在C++中,在用一個(gè)對(duì)象初始化另一個(gè)對(duì)象時(shí),只復(fù)制了成員,并沒(méi)有復(fù)制資源,使兩個(gè)對(duì)象同時(shí)指向了同一資源的復(fù)制方式稱為淺復(fù)制。
深拷貝是將指向內(nèi)容復(fù)制到給當(dāng)前對(duì)象新分配的緩沖區(qū)中的一種復(fù)制方式。
下面就是自己實(shí)現(xiàn)的深拷貝string類:
#include#include using namespace std; class String { public: String(const char* str="") :_str(new char[strlen(str)+1]) { strcpy(_str, str); } //深拷貝 String(const String& s) :_str(new char[strlen(s._str)+1]) { strcpy(_str, s._str); } String& operator=(const String& s) { if (this != &s) { delete[] _str; _str = new char[strlen(s._str) + 1]; strcpy(_str, s._str); } return *this; } ////現(xiàn)代寫(xiě)法 //String(const String& s) // :_str(NULL) //{ // String tmp(s._str); // swap(tmp._str,_str); //} //String& operator=(const String& s) //{ // if (this != &s) // { // _str = NULL; // String tmp(s); // swap(tmp._str, _str); // } // return *this; //} private: char* _str; };
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。