zoukankan      html  css  js  c++  java
  • share_ptr简单实现

    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;
    	}
    };
    
  • 相关阅读:
    费马小定理
    Big Number阶乘位数计算(斯特林公式)
    V
    矩阵快速幂求斐波那契
    奇迹
    缘分
    求导
    拓扑排序
    线段树
    单调栈
  • 原文地址:https://www.cnblogs.com/EvansPudding/p/12764905.html
Copyright © 2011-2022 走看看