首页 > 其他 > 详细

share_ptr简单实现

时间:2020-04-24 09:06:32      阅读:60      评论:0      收藏:0      [点我收藏+]
template<typename T>

class share_ptr {
private:
        //使用int *是为了每一个shared_ptr的count成员都指向同一个引用次数,每一个shared_ptr(绑定相同_ptr)操作的是同一个引用次数。
	int* count;//引用计数
	T* my_ptr; // 被封装的指针
public:
	//构造函数
	share_ptr(T* p)
		:count(new int(1)), my_ptr(p) {}
	~share_ptr() 
	{
		if (--*count == 0)
		{
			delete my_ptr;
			delete count;
		}
	}
	//
	int getRef() { return *count; }
	//运算符重载
	T* operator->() { return my_ptr; }
	T* operator*() { return *my_ptr; }

	//拷贝构造函数
	share_ptr(share_ptr<T>& other)
		:count(&(++*other.count)), my_ptr(other.my_ptr) {}
	
	share_ptr<T>& operator=(share_ptr<T>& other)
	{
		++* other.count; //复制的引用对象的计数增加
		//被赋值对象存在引用对象,且计数为1(更换引用对象后,清除之前的)
		if (this->my_ptr && 0 == -- * this->count)
		{
			delete count;
			delete _ptr;
		}
		this->my_ptr = other.my_ptr;
		this->count = other.count;
		return *this;
	}
};

share_ptr简单实现

原文:https://www.cnblogs.com/EvansPudding/p/12764905.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!