一、简介
- 采用了
COW写时复制
的方式实现,即在每个String类数据域之前用了4个字节的空间进行引用计数
。通过拷贝构造函数或者赋值运算符函数进行赋值时不会重新开辟空间,只会对引用计数加一,当有修改操作时,才会重新开辟新的空间;
- 内部定义了一个char类型的
内部代理类
,用于解决String类重载下标运算符后无法区分读写操作的问题。
二、头文件
#pragma once
#include <iostream>
class String {
class CharProxy {
public:
CharProxy(int index, String &str);
char &operator=(const char &c);
friend std::ostream &operator<<(std::ostream &os, const CharProxy &charPorxy);
private:
int _index;
String &_this;
};
public:
String();
String(const char *pstr);
String(const String &str);
~String();
String &operator=(const String &str);
String &operator=(const char *pstr);
String &operator+=(const String &str);
String &operator+=(const char *pstr);
String::CharProxy operator[](std::size_t index);
std::size_t size()const;
const char* c_str()const;
friend bool operator==(const String &leftStr, const String &rightStr);
friend bool operator!=(const String &leftStr, const String &rightStr);
friend bool operator<(const String &leftStr, const String &rightStr);
friend bool operator>(const String &leftStr, const String &rightStr);
friend bool operator<=(const String &leftStr, const String &rightStr);
friend bool operator>=(const String &leftStr, const String &rightStr);
friend std::ostream &operator<<(std::ostream &os, const String &str);
friend std::istream &operator>>(std::istream &is, String &str);
int refCount();
friend std::ostream &operator<<(std::ostream &os, const CharProxy &charPorxy);
private:
char *malloc(const char *pstr = nullptr);
void release();
void initRefCount();
void increaseRefCount();
void decreaseRefCount();<