重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
#define _CRT_SECURE_NO_WARNINGS #includeusing namespace std; #include //深拷貝 class String { public: String(const char* pData) : _pData(new char[strlen(pData) + 1]) { strcpy(_pData, pData); } String(const String& s)//拷貝構造,深拷貝,指針傳遞 : _pData(NULL) { String temp(s._pData); std::swap(_pData, temp._pData); } String& operator=(String s)//賦值運算符重載,深拷貝,值傳遞 { std::swap(_pData, s._pData); return *this; } ~String() { if (NULL != _pData) { delete[] _pData; _pData = NULL; } } private: char* _pData; };//深拷貝 //引用計數 namespace COW { class String { public: String(const char* pData) : _pData(new char[strlen(pData) + 1]) , _refCount(new int) { *_refCount = 1; strcpy(_pData, pData); } // String s2(s1); String(String& s)//s1和s2共用 : _pData(s._pData)//指向同一空間 , _refCount(s._refCount)//共用同一段引用計數 { ++(*_refCount); } // s1 = s2; String& operator=(String s) { if (this != &s) { if (--(*_refCount) == 0)//檢查這塊空間是否只有自己使用 { delete[] _pData; delete _refCount;//檢測完釋放歸還操作系統 } _pData = s._pData;//再指向另一塊空間 _refCount = s._refCount; ++(*_refCount); } return *this; } ~String() { if (--(*_refCount) == 0) { delete[] _pData; delete _refCount; } } private: char* _pData; int* _refCount; }; } //優化引用計數 class String { public: String(const char* pData) : _pData(new char[strlen(pData) + 5]) { *((int*)_pData) = 1; _pData += 4; // _pData = _pData + sizeof(char)*4; strcpy(_pData, pData); } // s2(s1); String(const String& s) : _pData(s._pData) { ++GetRef(); strcpy(_pData, s._pData); } // s2 = s3; String& operator=(const String& s) { if (this != &s) { if (--GetRef() == 0) { delete[](_pData - 4); } _pData = s._pData; ++GetRef(); } return *this; } ~String() { if (--GetRef() == 0) { delete[](_pData - 4); } } private: int& GetRef() { return (*((int*)(_pData - 4))); } private: char*_pData; }; 測試引用計數和深拷貝所用時間 class Time { public: Time() { begin = GetTickCount(); } ~Time() { int end = GetTickCount(); cout << "end - begin = " << end - begin << endl; } private: int begin; }; void FunTest() { Time t; COW::String s1("12345");//引用計數 COW::String s2(s1); for (int iIdx = 0; iIdx < 1000000; ++iIdx) { s1 = s2; } } void FunTest2() { Time t; String s1("123456789"); String s2("2345678"); for (int iIdx = 0; iIdx < 1000000; ++iIdx) { s1 = s2; } } int main() { FunTest(); FunTest2(); system("pause"); return 0; }
另外有需要云服務器可以了解下創新互聯scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業上云的綜合解決方案,具有“安全穩定、簡單易用、服務可用性高、性價比高”等特點與優勢,專為企業上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。