String浅拷贝---引用计数

本文介绍了一种使用引用计数解决C++中字符串类浅拷贝问题的方法。通过实现自定义的String类,文章详细展示了如何在构造函数、拷贝构造函数、赋值操作符和析构函数中正确地维护引用计数,确保对象引用的安全性和资源的正确释放。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当类里面有指针对象时,进行简单赋值的浅拷贝,两个对象指向同一块内存,存在崩溃的问题!为了解决这个问题,我们可以采用引用计数。

在引用计数中,每一个对象负责维护对象所有引用的计数值。当一个新的引用指向对象时,引用计数器就递增,当去掉一个引用时,引用计数就递减。当引用计数到零时,该对象就将释放占有的资源。

#include<iostream>
#include<Windows.h>
#include<string.h>
using namespace std;

class String
{
public:
	String(const char* str = "")
		:_str(new char[strlen(str) + 1])
	{
		strcpy(_str, str);
		++_GetRefCount ;
	}
	String(String& s)
		:_str(s._str)
	{
		++_GetRefCount;
	}
	String& operator=(const String&s)
	{
		if (this != &s)
		{
			this->~String();
			_str = s._str;
			++_GetRefCount;
		}
		return*this;
	}
	~String()
	{
		_Release();
	}
private:
	void _Release()
	{
		if (--_GetRefCount == 0)
		{
			delete[] _str;
			cout << "delete" << endl;
		}
	}
	friend ostream& operator<<(ostream& os, const String& s)
	{
		os << s._str;
		return os;
	}
private:
	char* _str;
	int _GetRefCount;//引用计数
};

void Test1()
{
	String s1("qwer");
	String s2(s1);
	cout << "s1:" << s1 << endl;
	cout << "s2:" << s2 << endl;

	String s3;
	s3 = s1;
	cout << "s3:" << s3 << endl;
}

int main()
{
	Test1();
	system("pause");
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值