string写时写时复制的实现

当两个std::string发生复制构造或者赋值时,不会复制字符串内容,而是增加一个引用计数,然后字符串指针进行浅拷贝,其执行效率为O(1)。只有当需要修改其中一个字符串内容时,才执行真正的复制

说明:std::string的首字母小写,为了区别于std::string,以下的String首字母大写

以下代码是其中的一种简单实现。

#include <string.h>
#include <iostream>

using std::cout;
using std::endl;

class String {
	public:
		String()
			: _pstr(new char[5]() + 4) {
			//开辟大小为5B的空间,一个int在前,一个char在后,并将指针移动到int
			cout << "String()" << endl;
			*(int *)(_pstr - 4) = 1;
		}
		
		//String str = "hello,world";
		String(const char *pstr)
			: _pstr(new char[strlen(pstr) + 5]() + 4) {
			cout << "String(const char *)" << endl;
			strcpy(_pstr, pstr);
			*(int *)(_pstr - 4) = 1;
		}

		//String s2 = s1;
		String(const String &rhs)
			: _pstr(rhs._pstr) {
			cout << "String(const String &)" << endl;
			++*(int *)(_pstr - 4);
		}

		//s3 = s1;
		String &operator=(const String &rhs) {
			cout << "String &operator=(const String &)" << endl;
			//1、自复制
			if (this != &rhs) {
				//2、释放左操作数
				--*(int *)(_pstr - 4);
				if (0 == *(int *)(_pstr - 4)) {
					delete [] (_pstr - 4);
				}

				//3、浅拷贝
				_pstr = rhs._pstr;
				++*(int *)(_pstr - 4);
			}

			//4、返回*this
			return *this;
		}

		//s3 = s1;
		//s3[0] = 'H'
		char &operator[](size_t idx) {
			if (idx < size()) {
				if (getRefCount() > 1) { //共享的
					//深拷贝
					char *tmp = new char[size() + 5]() + 4;
					strcpy(tmp, _pstr);
					//引用计数--
					--*(int *)(_pstr - 4);

					//浅拷贝
					_pstr = tmp;
					//初始化引用计数
					*(int *)(_pstr - 4) = 1;
				}
				return _pstr[idx];
			} else {
				static char charNull = '\0';
				return charNull;
			}
		}

		~String() {
			cout << "~String()" << endl;
			--*(int *)(_pstr - 4);
			if (0 == *(int *)(_pstr - 4)) {
				delete [] (_pstr - 4);
			}
		}

		//获取引用计数
		int getRefCount() const {
			return *(int *)(_pstr - 4);
		}

		//获取底层的指针
		const char *c_str() const {
			return _pstr;
		}

	private:
		size_t size() const {
			return strlen(_pstr);
		}

		friend std::ostream &operator<<(std::ostream &os, const String &rhs);
	private:
		char *_pstr;
};

std::ostream &operator<<(std::ostream &os, const String &rhs) {
	if (rhs._pstr) {
		os << rhs._pstr;
	}
	return os;
}

void test() {
	String s1("hello");
	cout << "s1 = " << s1 << endl;
	cout << "s1.getRefCount() = " << s1.getRefCount() << endl;
	printf("s1'address = %p\n", s1.c_str());

	cout << endl << endl;
	String s2 = s1;
	cout << "s1 = " << s1 << endl;
	cout << "s2 = " << s2 << endl;
	cout << "s1.getRefCount() = " << s1.getRefCount() << endl;
	cout << "s2.getRefCount() = " << s2.getRefCount() << endl;
	printf("s1'address = %p\n", s1.c_str());
	printf("s2'address = %p\n", s2.c_str());

	cout << endl << endl;
	String s3("world");
	cout << "s3 = " << s3 << endl;
	cout << "s3.getRefCount() = " << s3.getRefCount() << endl;
	printf("s3'address = %p\n", s3.c_str());

	cout << endl << endl;
	s3 = s1;
	cout << "s1 = " << s1 << endl;
	cout << "s2 = " << s2 << endl;
	cout << "s3 = " << s3 << endl;
	cout << "s1.getRefCount() = " << s1.getRefCount() << endl;
	cout << "s2.getRefCount() = " << s2.getRefCount() << endl;
	cout << "s3.getRefCount() = " << s3.getRefCount() << endl;
	printf("s1'address = %p\n", s1.c_str());
	printf("s2'address = %p\n", s2.c_str());
	printf("s3'address = %p\n", s3.c_str());

	cout << endl << "对s3[0]执行写操作" << endl;
	s3[0] = 'H';
	cout << "s1 = " << s1 << endl;
	cout << "s2 = " << s2 << endl;
	cout << "s3 = " << s3 << endl;
	cout << "s1.getRefCount() = " << s1.getRefCount() << endl;
	cout << "s2.getRefCount() = " << s2.getRefCount() << endl;
	cout << "s3.getRefCount() = " << s3.getRefCount() << endl;
	printf("s1'address = %p\n", s1.c_str());
	printf("s2'address = %p\n", s2.c_str());
	printf("s3'address = %p\n", s3.c_str());
}

int main(int argc, char **argv) {
	test();
	return 0;
}

代码重难点解析

构造函数

为了方便获取字符串的引用计数,比较好的解决方案是用字符串首地址的前四个字节记录引用计数,当读取引用计数的时候需要将这4字节按照int类型解释数据

String()
	: _pstr(new char[5]() + 4) {
	
	cout << "String()" << endl;
	*(int *)(_pstr - 4) = 1;
}

构造函数,先开辟一个5个字节的空间,为何是5个字节呢,该字符串的底层实现依赖于C语言的指针和string.h,C语言的字符串以空字符’\0’结尾,需要占用一个字节。_pstr(new char[5]() + 4) 该行代码的意思是先开辟一个5字节的空间,再将_pstr指向的位置后移4位,此时作为字符串的开始,而前四个字节用于保存引用计数。

构造函数(接收C风格字符串)

String(const char *pstr)
	: _pstr(new char[strlen(pstr) + 5]() + 4) {
	cout << "String(const char *)" << endl;
	strcpy(_pstr, pstr);
	*(int *)(_pstr - 4) = 1;
}

拷贝构造函数的调用时机总体来说归结为一句话,用一个已存在的对象初始化一个刚创建的对象,可以是在执行return返回一个类类型的临时对象,可以是函数调用形参实参结合,也可以说用一个已存在的对象给一个刚创建的对象赋值。

了解完拷贝构造函数。接下来开始分析该函数的难点。

strlen获取的是字符串有效字符个数,而字符串实际占用的空间为strlen得到的返回值+1,为何+1,因为C语言字符串以’\0’结尾,最后一字节存放空字符’\0’,根据之前的分析,引用计数需要占用4B,于是为了保存长度为strlen(pstr)的字符串,需要开辟长度为strlen(pstr)+5的空间。后面+4的原因还是因为前四个直接引用记录引用计数,字符串有效内容从第五个字节开始存放

*(int *)(_pstr - 4) = 1;难点解析,已知字符串从第五个字节开始存放数据,指针_pstr指向的是字符串的开始位置。字符串的前四个字节存放引用计数,该行代码的含义就是将字符串引用计数修改为1。_pstr - 4代表指针向前偏移4字节(char占1B,int占4B,偏移的是char类型的指针,再按照int的规则来解释数据,有点绕)

拷贝构造函数(接收String类型字符串)

String(const String &rhs)
: _pstr(rhs._pstr) {
	cout << "String(const String &)" << endl;
	++*(int *)(_pstr - 4);
}

用一个已有的String初始化刚创建的String,引用计数+1

赋值运算符函数

//s3 = s1;
String &operator=(const String &rhs) {
	cout << "String &operator=(const String &)" << endl;
	//1、自复制
	if (this != &rhs) {
		//2、释放左操作数
		--*(int *)(_pstr - 4);
		if (0 == *(int *)(_pstr - 4)) {
			delete [] (_pstr - 4);
		}

		//3、浅拷贝
		_pstr = rhs._pstr;
		++*(int *)(_pstr - 4);
	}

	//4、返回*this
	return *this;
}

需要考虑的问题:
1.自己给自己(自复制问题)
2.若被其他字符串赋值,引用计数减1,若引用计数为0则delete
3.执行浅拷贝操作,rhs字符串引用计数+1

重载下标访问运算符

//s3 = s1;
//s3[0] = 'H'
char &operator[](size_t idx) {
	if (idx < size()) {
		if (getRefCount() > 1) { //共享的
			//深拷贝
			char *tmp = new char[size() + 5]() + 4;
			strcpy(tmp, _pstr);
			//引用计数--
			--*(int *)(_pstr - 4);

			//浅拷贝
			_pstr = tmp;
			//初始化引用计数
			*(int *)(_pstr - 4) = 1;
		}
		return _pstr[idx];
	} else {
		static char charNull = '\0';
		return charNull;
	}
}

重载下标访问运算符,使其可以向访问数组元素一样访问字符串内的字符。

析构函数

~String() {
	cout << "~String()" << endl;
	--*(int *)(_pstr - 4);
	if (0 == *(int *)(_pstr - 4)) {
		delete [] (_pstr - 4);
	}
}

析构函数,若字符串引用计数不为0,则将引用计数减一,若引用计数为0则执行delete

重载输出流运算符

std::ostream &operator<<(std::ostream &os, const String &rhs) {
	if (rhs._pstr) {
		os << rhs._pstr;
	}
	return os;
}

cout不支持直接输出String对象的值,重载输出流运算符,使其可以直接输出String对象的值

其他函数

//获取引用计数
int getRefCount() const {
	return *(int *)(_pstr - 4);
}

//获取底层的指针(转为C风格字符串)
const char *c_str() const {
	return _pstr;
}

//获取字符串长度
size_t size() const {
	return strlen(_pstr);
}

本文的代码有一个隐含的bug,对于下标访问运算,写操作正常,但读操作会部分异常情况(读到的值正常,但发生了字符串拷贝操作,读操作不应该发生拷贝),该问题的解决方案及优化方案将在下一个版本发布。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值