为实现祖国统一而奋斗!为实现社会主义现代化而奋斗!为实现中华民族复兴而奋斗!
——By 一名社会主义建设积极分子
GIF:
目录
https://blog.csdn.net/m0_57859086/article/details/126124276
后记:●由于作者水平有限,文章难免存在谬误之处,敬请读者斧正,俚语成篇,恳望指教! ——By 作者:新晓·故知
<string类模拟实现>——《C++初阶》链接:
https://blog.csdn.net/m0_57859086/article/details/126124276
1. string类的模拟实现
1.1 经典的string类问题
上面已经对string类进行了简单的介绍,只要能够正常使用即可。在面试中,面试官总喜欢让学生自己来模拟实现string类,最主要是实现string类的构造、拷贝构造、赋值运算符重载以及析构函数。大家看下以下string类的实现是否有问题?class string { public: /*string() :_str(new char[1]) {*_str = '\0';} */ //string(const char* str = "\0") 错误示范 //string(const char* str = nullptr) 错误示范 string(const char* str = "") { // 构造string类对象时,如果传递nullptr指针,认为程序非法,此处断言下 if (nullptr == str) { assert(false); return; } _str = new char[strlen(str) + 1]; strcpy(_str, str); } ~string() { if (_str) { delete[] _str; _str = nullptr; } } private: char* _str; }; // 测试 void Teststring() { string s1("hello bit!!!"); string s2(s1); }
说明:上述string类没有显式定义其拷贝构造函数与赋值运算符重载,此时编译器会合成默认的,当用s1构造s2时,编译器会调用默认的拷贝构造。最终导致的问题是,s1、s2共用同一块内存空间,在释放时同一块空间被释放多次而引起程序崩溃,这种拷贝方式,称为浅拷贝。
1.2 浅拷贝
浅拷贝:也称位拷贝,编译器只是将对象中的值拷贝过来。如果对象中管理资源,最后就会导致多个对象共享同一份资源,当一个对象销毁时就会将该资源释放掉,而此时另一些对象不知道该资源已经被释放,以为还有效,所以 当继续对资源进项操作时,就会发生发生了访问违规。要解决浅拷贝问题,C++中引入了深拷贝。
1.3 深拷贝
如果一个类中涉及到资源的管理,其拷贝构造函数、赋值运算符重载以及析构函数必须要显式给出。一般情况都是按照深拷贝方式提供。
1.3.1 传统版写法的string类
class string { public: string(const char* str = "") { // 构造string类对象时,如果传递nullptr指针,认为程序非法,此处断言下 if (nullptr == str) { assert(false); return; } _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) { char* pStr = new char[strlen(s._str) + 1]; strcpy(pStr, s._str); delete[] _str; _str = pStr; } return *this; } ~string() { if (_str) { delete[] _str; _str = nullptr; } } private: char* _str; };
1.3.2 现代版写法的string类
class string { public: string(const char* str = "") { if (nullptr == str) str = ""; _str = new char[strlen(str) + 1]; strcpy(_str, str); } string(const string& s) : _str(nullptr) { string strTmp(s._str); swap(_str, strTmp._str); } // 对比下和上面的赋值那个实现比较好? string& operator=(string s) { swap(_str, s._str); return *this; } /* string& operator=(const string& s) { if(this != &s) { string strTmp(s); swap(_str, strTmp._str); } return *this; } */ ~string() { if (_str) { delete[] _str; _str = nullptr; } } private: char* _str; };
1.3.3写时拷贝(了解)
写时拷贝就是一种拖延症,是在浅拷贝的基础之上增加了引用计数的方式来实现的。引用计数:用来记录资源使用者的个数。在构造时,将资源的计数给成1,每增加一个对象使用该资源,就给计数增加1,当某个对象被销毁时,先给该计数减1,然后再检查是否需要释放资源,如果计数为1,说明该对象时资源的最后一个使用者,将该资源释放;否则就不能释放,因为还有其他对象在使用该资源。链接:写时拷贝在读取是的缺陷: C++的std::string的“读时也拷贝”技术!
1.4 string类的模拟实现
namespace bit { class string { public: typedef char* iterator; public: string(const char* str = "") { _size = strlen(str); _capacity = _size; _str = new char[_capacity + 1]; strcpy(_str, str); } string(const string& s) : _str(nullptr) , _size(0) , _capacity(0) { string tmp(s._str); this->swap(tmp); } string& operator=(string s) { this->swap(s); return *this; } ~string() { if (_str) { delete[] _str; _str = nullptr; } } / // iterator iterator begin() { return _str; } iterator end() { return _str + _size; } / // modify void push_back(char c) { if (_size == _capacity) Reserve(_capacity * 2); _str[_size++] = c; _str[_size] = '\0'; } string& operator+=(char c) { PushBack(c); return *this; } // 作业实现 void append(const char* str); string& operator+=(const char* str); void clear() { _size = 0; _str[_size] = '\0'; } void swap(string& s) { swap(_str, s._str); swap(_size, s._size); swap(_capacity, s._capacity); } const char* c_str()const { return _str; } / // capacity size_t size()const; size_t capacity()const; bool empty()const void resize(size_t newSize, char c = '\0') { if (newSize > _size) { // 如果newSize大于底层空间大小,则需要重新开辟空间 if (newSize > _capacity) { Reserve(newSize); } memset(_str + _size, c, newSize - _size); } _size = newSize; _str[newSize] = '\0'; } void reserve(size_t newCapacity) { // 如果新容量大于旧容量,则开辟空间 if (newCapacity > _capacity) { char* str = new char[newCapacity + 1]; strcpy(str, _str); // 释放原来旧空间,然后使用新空间 delete[] _str; _str = str; _capacity = newCapacity; } } // access char& operator[](size_t index) { assert(index < _size); return _str[index]; } const char& operator[](size_t index)const { assert(index < _size); return _str[index]; } // 作业 bool operator<(const string& s); bool operator<=(const string& s); bool operator>(const string& s); bool operator>=(const string& s); bool operator==(const string& s); bool operator!=(const string& s); // 返回c在string中第一次出现的位置 size_t find(char c, size_t pos = 0) const; // 返回子串s在string中第一次出现的位置 size_t find(const char* s, size_t pos = 0) const; // 在pos位置上插入字符c/字符串str,并返回该字符的位置 string& insert(size_t pos, char c); string& insert(size_t pos, const char* str); // 删除pos位置上的元素,并返回该元素的下一个位置 string& erase(size_t pos, size_t len); private: friend ostream& operator<<(ostream& _cout, const bit::string& s); friend istream& operator>>(istream& _cin, bit::string& s); private: char* _str; size_t _capacity; size_t _size; }; } ostream& bit::operator<<(ostream& _cout, const bit::string& s) { // 不能使用这个 //cout << s._str; for (size_t i = 0; i < s.size(); ++i) { _cout << s[i]; } return _cout; } ///对自定义的string类进行测试 void TestBitstring() { bit::string s1("hello"); s1.push_back(' '); s1.push_back('b'); s1.append(1, 'i'); s1 += 't'; cout << s1 << endl; cout << s1.size() << endl; cout << s1.capacity() << endl; // 利用迭代器打印string中的元素 string::iterator it = s1.begin(); while (it != s1.end()) { cout << *it << " "; ++it; } cout << endl; // 这里可以看到一个类只要支持的基本的iterator,就支持范围for for (auto ch : s1) cout << ch << " "; cout << endl; }