基于引用计数的智能指针

#pragma once
#include<iostream>
#include<string>
using namespace std;

template<typename T>
class SmartPointer
{
	//不允许有SmartPointer sp=new T()这样的使用方式能给sp赋值的只有另一个sp对象和构造方法
public:
	SmartPointer(T* p = 0) :ptr(p), ref_count(new size_t)//构造函数
	{
		if (ptr)
			*ref_count = 1;
	}
	SmartPointer(SmartPointer& src)//拷贝构造函数
	{
		if (this != &src)
		{
			ptr = src.ptr;
			ref_count = src.ref_count;
			(*ref_count)++;
		}
	}
	T& operator*()//操作符重载,注意返回类型
	{
		if (ptr)
			return *ptr;
		//throw exception;
	}
	T* operator->()//操作符重载,注意返回类型
	{
		if (ptr)
			return ptr;
		//throw exception;
	}
	SmartPointer& operator=(SmartPointer& src)//操作符重载,注意返回类型
	{
		if (this == &src)
			return *this;
		releaseCount();
		ptr = src.ptr;
		ref_count = src.ref_count;
		(*ref_count)++;
		return *this;
	}
	int getRefCount(){ return *ref_count; }//返回计数值
	~SmartPointer(){ releaseCount(); }//析构函数
private:
	T* ptr;
	size_t* ref_count;
	void releaseCount()//计数减一,若减一后为0,释放内存
	{
		if (ptr && --(*ref_count) == 0)
		{
			delete ptr;
			delete ref_count;
		}
	}
};

void main()
{
	SmartPointer<string> cp1(new string("a"));
	cout << *cp1 << endl;
	cout << cp1->size() << endl;
	SmartPointer<string> cp2(cp1);
	cout << *cp1 << endl;
	cout << cp1->size() << endl;
	cout << cp1.getRefCount() << endl;
	SmartPointer<string> cp3;
	cp3 = cp2;
	cp3 = cp1;
	cp3 = cp3;
	cout << cp3.getRefCount() << endl;
	SmartPointer<string> cp4(new string("b"));
	cp3 = cp4;
	cout << cp1.getRefCount() << endl;
	
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值