【C++】String类拷贝构造函数——浅拷贝优化的三种方式(引用计数)

这里提供三种优化方式:

1.使用静态变量计数

2.单独开辟计数空间

3.对象和计数变量使用同一连续空间


代码示例:

第一种

class String
{
public:
	String(char* pStr = "")
		:_pStr(new char[strlen(pStr)+1])
	{
		strcpy(_pStr, pStr);
		_pCount++;
	}

	String(String& s)
		:_pStr(s._pStr)
	{
		_pCount++;
	}
	//赋值运算符重载只有面对同一个对象,无需重写
	~String()
	{
		if (--_pCount == 0)
		{
			delete[] _pStr;
		}
	}
private:
	char* _pStr;
	static int _pCount;
};
int String::_pCount = 0;

第二种:

使用单独内存的引用计数
class String
{
public:
	String(char* pStr = "")
		:_pStr(new char[strlen(pStr) + 1])
		,_pCount(new int(1))
	{
		strcpy(_pStr, pStr);
	}

	String(String& s)
		:_pStr(s._pStr)
	{
		_pCount++;
	}
	String& operator=(const String& s)
	{
		if (_pStr != s._pStr)
		{
			Delete();
			_pStr = s._pStr;
			_pCount = s._pCount;
			_pCount++;
		}
		return *this;
	}
	~String()
	{
		Delete();
	}
private:
	void Delete()
	{
		if (0 == (--(*_pCount)))
		{
			delete[] _pStr;
			delete _pCount;
		}
	}
private:
	char* _pStr;
	int* _pCount;
};

第三种:

//在同一空间中使用引用计数—— _pCount ====(int*)(_pStr-4)
class String
{
public:
	String(char* pStr = "")
		:_pStr(new char[strlen(pStr) + 5])
	{
		*_pStr = 1;
		_pStr -= 4;
		strcpy(_pStr, pStr);
	}

	String(String& s)
		:_pStr(s._pStr)
	{
		//++(*((int*)(_pStr - 4)));
		++GetRefCount();
	}
	String& operator=(const String& s)
	{
		if (_pStr != s._pStr)
		{
			Delete();
			_pStr = s._pStr;
			//_pCount = s._pCount;
			//_pCount++;
			++GetRefCount();

		}
		return *this;
	}
	~String()
	{
		Delete();
	}
private:
	void Delete()
	{
		if (0 == (--(GetRefCount())))
		{
			delete[] (_pStr-4);
			//delete _pCount;
		}
	}
	int& GetRefCount()
	{
		return *((int*)(_pStr - 4));
	}
private:
	char* _pStr;
};

void fun1()
{
	String s1("hello");
	String s2(s1);
	s2 = s1;
}


void fun2()
{
	String s1("hello");
	String s2(s1);
	
	String s3("world");
	String s4(s3);

	s3 = s2;
}

void fun3()
{
	String s1("hello");
	String s2("world");
	s2 = s1;
}
int main()
{
	fun1();
	fun2();
	fun3();
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值