
系列文章目录
前言

一、string类的模拟实现
1.经典的string类问题
上篇文章已经对string类进行了简单的介绍,大家只要能够正常使用即可。在面试中,面试官总喜欢让学生自己来模拟实现string类,最主要是实现string类的构造、拷贝构造、赋值运算符重载以及析构函数。大家看下以下string类的实现是否有问题?
nclude<iostream>
namespace yyw
{
class string
{
public:
string()
:_str(new char[1])
{
_str[0] = '\0';
}
string(char* str)
:_str(new char[strlen(str)+1])
{
strcpy(_str, str);
}
size_t size()
{
return strlen(_str);
}
bool empty()
{
return _str == nullptr;
}
char& operator[](size_t i)
{
return _str[i];
}
~string()
{
if (_str)
{
delete[] _str;
_str = nullptr;
}
}
const char* c_str()
{
return _str;
}
private:
char* _str;
};
void TestString1()
{
string s1("hello");
string s2;
for (size_t i = 0; i < s1.size(); i++)
{
s1[i] += 1;
std::cout << s1[i] << " ";
}
std::cout << std::endl;
for (size_t i = 0; i < s2.size(); i++)
{
s2[i] += 1;
std::cout << s2[i] << " ";
}
std::cout << std::endl;
}
void TestString2()
{
string s1("hello");
string s2(s1);
std::cout << s1.c_str() << std::endl;
std::cout << s2.c_str() << std::endl;
string s3("world");
s1 = s3;
std::cout << s1.c_str() << std::endl;
std::cout << s3.c_str() << std::endl;
}
}
默认的拷贝的构造函数出现的问题。  默认的赋值运算符重载出现的问题。   说明:上述string类没有显式定义其拷贝构造函数与赋值运算符重载,此时编译器会合成默认的,当用s1构造s2时,编译器会调用默认的拷贝构造。最终导致的问题是,s1、s2共用同一块内存空间,在释放时同一块空间被释放多次而引起程序崩溃,这种拷贝方式,称为浅拷贝。
2.浅拷贝
浅拷贝:也称位拷贝,编译器只是将对象中的值拷贝过来。如果对象中管理资源,最后就会导致多个对象共享同一份资源,当一个对象销毁时就会将该资源释放掉,而此时另一些对象不知道该资源已经被释放,以为还有效,所以 当继续对资源进项操作时,就会发生发生了访问违规。要解决浅拷贝问题,C++中引入了深拷贝。
3.深拷贝

4.传统版的string类
C++ 的一个常见面试题是让你实现一个 String 类,限于时间,不可能要求具备 std::string 的功能,但至少要求能正确管理资源。 具体来说:能像 int 类型那样定义变量,并且支持赋值、复制。能用作函数的参数类型及返回类型。能用作标准库容器的元素类型,即 vector / list / deque 的 value_type。(用作 std::map 的 key_type 是更进一步的要求,本文从略)。换言之,你的 String 能让以下代码编译运行通过,并且没有内存方面的错误。
#include<iostream>
namespace yyw
{
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)
{
char* tmp = new char[strlen(s._str) + 1];
strcpy(tmp,s._str);
delete[] _str;
_str = tmp;
}
return *this;
}
~string()
{
if(_str)
{
delete[] _str;
_str = nullptr;
}
}
char& operator[](size_t i)
{
return _str[i];
}
size_t size()
{
return strlen(_str);
}
private:
size_t _size;
char* _str;
};
void TestString1()
{
string s1;
string s2("hello");
for (size_t i = 0; i < s2.size(); i++)
{
std::cout << s2[i] << " ";
}
std::cout << std::endl;
s1 = s2;
for (size_t i = 0; i < s1.size(); i++)
{
std::cout << s1[i] << " ";
}
}
}
测试代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include"string.h"
int main()
{
yyw::TestString1();
return 0;
}

5.现代版的string类
#include<iostream>
#include<algorithm>
namespace yyw
{
class string
{
public:
string(const char* str = "")
:_str(new char[strlen(str)+1])
{
strcpy(_str, str);
}
string(const string& s)
:_str(nullptr)
{
string tmp(s._str);
std::swap(_str, tmp._str);
}
string& operator=(const string& s)
{
if (this != &s)
{
string tmp(s._str);
std::swap(_str, tmp._str);
}
return *this;
}
string& operator=(string s)
{
std::swap(_str, s._str);
return *this;
}
~string()
{
if (_str)
{
delete[] _str;
_str = nullptr;
}
}
private:
char* _str;
};
void TestString1()
{
string s1;
string s2("hello");
string s3(s2);
s1 = s3;
}
}

6. 写时拷贝(了解)
 写时拷贝就是一种拖延症,是在浅拷贝的基础之上增加了引用计数的方式来实现的。 引用计数:用来记录资源使用者的个数。在构造时,将资源的计数给成1,每增加一个对象使用该资源,就给计数增加1,当某个对象被销毁时,先给该计数减1,然后再检查是否需要释放资源,如果计数为1,说明该对象时资源的最后一个使用者,将该资源释放;否则就不能释放,因为还有其他对象在使用该资源。
7. string类的模拟实现
测试代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include"string.h"
int main()
{
yyw::TestString1();
yyw::string s3("hello");
yyw::string::iterator it = s3.begin();
while (it != s3.end())
{
std::cout << *it << " ";
it++;
}
std::cout << std::endl;
for (auto e : s3)
{
std::cout << e << " ";
}
std::cout << std::endl;
yyw::TestString2();
yyw::TestString3();
return 0;
}
头文件代码:
#include<iostream>
#include<assert.h>
namespace yyw
{
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=(const string& s)
{
string tmp(s._str);
this->swap(tmp);
return *this;
}
void swap(string &s)
{
std::swap(_str, s._str);
std::swap(_size, s._size);
std::swap(_capacity, s._capacity);
}
~string()
{
if (_str)
{
delete[] _str;
_size = _capacity = 0;
_str = nullptr;
}
}
void push_back(char ch)
{
if (_size == _capacity)
{
size_t newcapacity = _capacity == 0 ? 6 : _capacity * 2;
char* tmp = new char[newcapacity + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = newcapacity;
}
_str[_size] = ch;
_size++;
_str[_size] = '\0';
}
void append(char* str)
{
size_t len = strlen(str);
if (_size + len > _capacity)
{
size_t newcapacity = _size + len;
char* tmp = new char[newcapacity + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = newcapacity;
}
strcpy(_str + _size, str);
_size += len;
}
string& operator+=(char ch)
{
this->push_back(ch);
return *this;
}
string& operator+=(char* ch)
{
this->append(ch);
return *this;
}
string& insert(size_t pos, char ch)
{
assert(pos <= _size);
if (_size == _capacity)
{
size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;
char* tmp = new char[newcapacity + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = newcapacity;
}
size_t end = _size;
while (end >= (int)pos)
{
_str[end + 1] = _str[end];
end--;
}
_str[pos] = ch;
_size++;
return *this;
}
string& insert(size_t pos, char* str)
{
assert(pos < _size);
size_t len = strlen(str);
if (_size + len>_capacity)
{
size_t newcapacity = _size + len;
char* tmp = new char[newcapacity + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = newcapacity;
}
size_t end = _size;
while (end >= (int)pos)
{
_str[end + len] = _str[end];
end--;
}
for (size_t i = 0; i < len; i++)
{
_str[pos] = str[i];
pos++;
}
_size += len;
return *this;
}
string& erase(size_t pos, size_t len=npos)
{
assert(pos < _size);
if (len >= _size - pos)
{
_str[pos] = '\0';
_size = pos;
}
else
{
size_t i = pos + len;
while (i <= _size)
{
_str[i - len] = _str[i];
i++;
}
_size = _size - len;
}
return *this;
}
size_t find(char ch, size_t pos)
{
for (size_t i = pos; i < _size; i++)
{
if (_str[i] == ch)
{
return i;
}
}
return npos;
}
size_t find(char* str, size_t pos)
{
char* p = strstr(_str, str);
if (p == NULL)
{
return npos;
}
else
{
return (p - str);
}
}
void resize(size_t newsize, char ch = '\0')
{
if (newsize<_size)
{
_str[newsize] = '\0';
_size = newsize;
}
else
{
if (newsize > _capacity)
{
size_t newcapacity = newsize;
char* tmp = new char[newcapacity];
strcpy(tmp, _str);
delete[]_str;
_str = tmp;
_capacity = newcapacity;
}
for (size_t i = _size; i < newsize; i++)
{
_str[i] = ch;
}
_size = newsize;
_str[_size] = '\0';
}
}
iterator begin()
{
return _str;
}
iterator end()
{
return (_str + _size);
}
const char* c_str()
{
return _str;
}
char& operator[](size_t i)
{
assert(i < _size);
return _str[i];
}
const char& operator[](size_t i) const
{
assert(i < _size);
return _str[i];
}
bool operator<(const string& s)
{
int ret = strcmp(_str, s._str);
return ret < 0;
}
bool operator<=(const string& s)
{
return *this<s || *this == s;
}
bool operator>(const string& s)
{
return !(*this <= s);
}
bool operator>=(const string& s)
{
return !(*this < s);
}
bool operator==(const string& s)
{
int ret = strcmp(_str, s._str);
return ret == 0;
}
bool operator!=(const string& s)
{
return !(*this == s);
}
bool empty()
{
return _size == 0;
}
size_t size()
{
return _size;
}
size_t capacity()
{
return _capacity;
}
private:
char* _str;
size_t _size;
size_t _capacity;
static size_t npos;
};
size_t string::npos = -1;
std::ostream& operator<<(std::ostream& _out, string& s)
{
for (size_t i = 0; i < s.size(); i++)
{
std::cout << s[i];
}
return _out;
}
std::istream& operator>>(std::istream& _in, string &s)
{
while (1)
{
char ch;
ch = _in.get();
if (ch == ' ' || ch == '\n')
{
break;
}
else
{
s += ch;
}
}
return _in;
}
void TestString1()
{
string s1;
string s2("bit");
for (size_t i = 0; i < s1.size(); i++)
{
std::cout << s1[i] << " ";
}
std::cout << std::endl;
for (size_t i = 0; i < s2.size(); i++)
{
std::cout << s2[i] << " ";
}
std::cout << std::endl;
}
void TestString2()
{
string s1;
string s2("bit");
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
s1.push_back('b');
std::cout << s1 << std::endl;
s2.push_back(' ');
std::cout << s2 << std::endl;
s1.append("hha");
std::cout << s1 << std::endl;
s2.append("education");
std::cout << s2 << std::endl;
s1 += 'a';
std::cout << s1 << std::endl;
s2 += "a";
std::cout << s2 << std::endl;
s2.insert(1, 'a');
std::cout << s2 << std::endl;
s2.insert(1, "www");
std::cout << s2 << std::endl;
std::cout << s2.size() << std::endl;
std::cout << s2.capacity() << std::endl;
}
void TestString3()
{
string s1;
std::cin >> s1;
std::cout << s1 << std::endl;
}
}
总结
以上就是今天要讲的内容,本文简单介绍了string类的常见问题和模拟实现,而string类提供了大量能使我们快速便捷地处理数据的函数和方法,非常的便捷,所以我们务必掌握。另外如果上述有任何问题,请懂哥指教,不过没关系,主要是自己能坚持,更希望有一起学习的同学可以帮我指正,但是如果可以请温柔一点跟我讲,爱与和平是永远的主题,爱各位了。 
|