一、简介
- 采用了COW写时复制的方式实现,即在每个string类数据域之前用了4个字节的空间进行引用计数。通过拷贝构造函数或者赋值运算符函数进行赋值时不会重新开辟空间,只会对引用计数加一,当有修改操作时,才会重新开辟新的空间;
- 内部定义了一个char类型的内部代理类,用于解决String类重载下标运算符后无法区分读写操作的问题。
#pragma once
#include
class String {
class CharProxy { // char类型的代理内部类
public:
CharProxy(int index, String &str);
char &operator=(const char &c);
friend std::ostream &operator
cout
cout // 未越界
if (*(int*)(_this._pstr - refCountLength) 1) { // 判断引用计数是否大于1
_this.decreaseRefCount(); // 原空间引用计数-1
char *newStr = _this.malloc(_this._pstr); // 开辟新空间
strcpy(newStr, _this._pstr);
_this._pstr = newStr;
_this.initRefCount(); // 初始化引用计数(此处时机一定要在赋值了新串之后)
}
_this._pstr[_index] = c; // 修改元素
return _this._pstr[_index];
}else {
static char nullchar = '\0';
return nullchar;
}
}
/**
* 重载内部代理类的输出运算符
if (charPorxy._index