12.9 智能指针

     《程序员面试金典》(第六版)习题:仅为记录一下以加强印象,不为商业用途,如有侵权请联系删除。以下源码和解释参考了书中源码以及解释。
     这里相当于是自己实现一个智能指针。智能指针主要用于方便动态内存的管理,如果自己手动使用 n e w new new d e l e t e delete delete m a l l o c malloc malloc f r e e free free来管理动态内存的话比较困难,因为很难知道具体在哪个地方释放内存,这就会造成内存泄漏等问题。智能指针允许多个指针指向同一个对象并维持一个引用计数来记录目前对象T被引用的次数,当引用计数为0时表明此时已经没有引用对象T的地方,这时会自动释放对象T的内存,而不用手动去处理。其实在 c + + c++ c++ m e m o r y memory memory头文件中已经有现成的智能指针 s t d : : s h a r e d _ p t r std::shared\_ptr std::shared_ptr,具体可以查看这里这里

template<class T> class SmartPointer
{
protected:
	T* ref;//指向的对象
	unsigned* refCount;//引用计数
	void remove()
	{
		--(*refCount);
		if (*refCount == 0)//引用计数为0时
		{
			delete ref;
			free(refCount);
			ref = nullptr;
			refCount = nullptr;
		}
	}
public:
	SmartPointer(T* ptr)
	{
		ref = ptr;
		refCount = (unsigned*)malloc(sizeof(unsigned));
		*refCount = 1;
	}

	SmartPointer(SmartPointer<T>& sptr)
	{
		ref = sptr.ref;
		refCount = sptr.refCount;
		++(*refCount);
	}

	SmartPointer<T>& operator=(SmartPointer<T> & sptr)
	{
		if (this == &sptr)
			return *this;
		if (*refCount > 0)
			remove();

		ref = sptr.ref;
		refCount = sptr.refCount;
		++(*refCount);
		return *this;
	}
	~SmartPointer()
	{
		remove();
	}
	T getValue()
	{
		return *ref;
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qqssss121dfd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值