1. 实现 C++ string 类

1.1 C++ 中动态内存管理

1.2 深拷贝和浅拷贝

1.3 运算符重载

1.4 移动语义与右值引用

1.5 智能指针

img

参考链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
namespace W
{
class String {
public:
size_t capacity;
char* _str;
size_t _size;
//构造函数
String(const char* str = "") {
_size = strlen(str);
capacity = _size;
_str = new char[_size + 1]; // 多开一个空间,用来存放 '\\0'
strcpy(_str, str);
}
//默认构造函数,浅拷贝,两个对象指向同一块内存
String(const String& s) {
_str = s._str;
_size = s._size;
capacity = s.capacity;
}

String& operator=(const String& s) {
if (this != &s) {
delete[] _str;
capacity = s.capacity;
_size = s._size;
_str = new char[capacity + 1];
strcpy(_str, s._str);
}
return *this;
}
//赋值运算符返回的是引用,因为可以连续赋值
//深拷贝,两个对象指向不同的内存,避免浅拷贝的问题

~String() {
delete[] _str;
_str = nullptr;
_size = 0;
capacity = 0;
}

};
}

2. 其他要点

  1. 引用、指针、对象与地址的关系
  2. *(待补充)