C++中的写时拷贝技术

一:概念解释

  当我们在构造一个对象时,我们需要把所有的成员变量和成员方法都要统统的给这个对象构造出来,那么如果这个对象我们别不需要对它进行读取和修改的操作,那么我们是不是可以采用一种写时拷贝技术来减少内存的消耗?

二:代码分析

#include<iostream>
using namespace std;
#include<string>
class CString
{
public:
	CString()
	{
		_str = new char[5];
		_str[4] = 0;//加上结束字符0
		getcount() = 1;//将标志位设置为1
	}
	CString(const char* str)
	{
		_str = new char[strlen(str) + 4 + 1];//4是标志为的大小,1是最后的结束字符'\0'大小
		strncpy_s(_str + 4, strlen(str) + 1, str, strlen(str));//?
		getcount() = 1;
	}
	CString(const CString& src)//拷贝构造函数
	{
		//让两个类对象中的成员变量指向同一个外部资源
		_str = src._str;
		//又多了一个类对象使用该外部资源。
		getcount()++;
	}
	CString& operator=(const CString& src)//等号运算符的重载
	{
		if (this == &src)
		{
			return *this;
		}
		if (--getcount() == 0)
		{
			delete[]_str;
		}
		_str = src._str;
		getcount()++;

		return *this;
	}
	~CString()
	{
		if (--getcount() == 0)
		{
			delete[]_str;
		}
	}
	//当我们试图改变该外部资源时 我们需要经行  写时拷贝技术
	char& operator[](int pos)
	{
		if (getcount() > 1)
		{
			getcount()--;
			char* tmp = this->_str;

			_str = new char[strlen(tmp + 1) + 4 + 1];
			strncpy_s(_str + 4, strlen(tmp + 4) + 1, tmp + 4, strlen(tmp + 4));
			getcount() = 1;
		}
		return _str[pos + 4];
	}
	void show()
	{
		cout << this->_str+4 << endl;
	}
private:
	int& getcount()
	{
		return *(int*)_str;//将字符数组的前四个字节获取到,以int类型作为标志
	}
	char* _str;

};
int main()
{
	CString my1;
	my1 = "wangbao";
	my1.show();
	CString my2 = my1;
	my2.show();
	my2[1] = 's';
	my2.show();

	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值