/* 优化string 复制的时候 仅复制引用,只有在修改内容时,才复制内容 即实现写时拷贝 */ class COWMyString { public: //默认参数 COWMyString(const char *str = "") :m_str(strcpy(new char[strlen(str) + 1], str)) { if (m_str) { m_count = new size_t(1); } else { m_count = new size_t(0); } } ~COWMyString(void) { (*this->m_count)--; if (*this->m_count == 0) { delete []this->m_str; delete this->m_count; } } //深拷贝构造 COWMyString(const COWMyString&that) { if (this != &that) { this->m_str = that.m_str; //指针指向的实际上是同一个计数器,同一块内存 this->m_count = that.m_count; (*this->m_count)++; } } //深拷贝赋值 COWMyString&operator=(const COWMyString&that) { //指针指向的实际上是同一个计数器,同一块内存 if (this->m_str == that.m_str) { return *this; } if (this->m_str) { //将原来的引用计数减一 (*this->m_count)--; if (this->m_count == 0) { delete []this->m_str; delete this->m_count; } this->m_str = that.m_str; //指针指向的实际上是同一个计数器,同一块内存 this->m_count = that.m_count; (*this->m_count)++; } return *this; } //copy on write char &operator[](size_t index) { if (index>strlen(m_str)) { static char nullchar = 0; return nullchar; } (*this->m_count)--; m_str = strcpy(new char[strlen(m_str)+1], m_str); m_count = new size_t(1); return *(m_str + index); } const char *c_str(void)const { return m_str; } private: //指针 char* m_str; //计数器 size_t* m_count; };