• 一个shared_ptr的简易实现


    #include<iostream>
    
    
    class SharedCount{
    public:
    	SharedCount():count_(1){}
    	void AddCount(){
    		++count_;
    	}
    	long ReduceCount(){
    		return --count_;
    	}
    	long GetCount() const{
    		return count_;
    	}
    
    	template<typename T>
    	friend class SharedPtr;
    
    private:
    	long count_;
    };
    
    
    template<typename T>
    class SharedPtr{
    public:
    	explicit SharedPtr(T *ptr=nullptr):ptr_(ptr){
    		if(ptr_){
    			rel_ = new SharedCount();
    		}else{
    			rel_ = nullptr;
    		}
    	};
    
    	~SharedPtr(){
    		if(rel_ && !rel_->ReduceCount()){
    			delete ptr_;
    			delete rel_;
    		}
    	}
    
    	SharedPtr(const SharedPtr& other){
    		rel_ = other.rel_;
    		if(rel_){
    			rel_->AddCount();
    		}
    		ptr_ = other.ptr_;
    	}
    
    
    	SharedPtr(SharedPtr&& other){
    		ptr_ = other.ptr_;
    		rel_ = other.rel_;
    
    		other.ptr_ = nullptr;
    		other.res_ = nullptr;
    	}
    
    	SharedPtr& operator=(SharedPtr& rhs){
    		if(ptr_ != rhs.ptr_){
    			if(rel_ && !rel_->ReduceCount()){
    				delete ptr_;
    				delete rel_;
    			}
    			rhs.rel_->AddCount();
    			ptr_ = rhs.ptr_;
    			rel_ = rhs.rel_;
    		}
    
    		return *this;
    	}
    
    	T* Get() const{
    		return ptr_;
    	}
    
    	long UseCount() const{
    		if(ptr_){
    			return rel_->GetCount();
    		}else{
    			return 0;
    		}
    	}
    
    
    	T& operator*() const{
    		return *ptr_;
    	}
    	T* operator->() const{
    		return ptr_;
    	}
    	operator bool() const{
    		return ptr_;
    	}
    
    
    private:
    	T *ptr_;
    	SharedCount *rel_;
    };
    
    
    int main(){
    	SharedPtr<int> sp1(new int(5));
    	SharedPtr<int> sp2;
    	std::cout << "sp1.use_count:  " << sp1.UseCount() << std::endl;
    	std::cout << "sp2.use_count:  " << sp2.UseCount() << std::endl;
    
    	sp2 = sp1;
    	std::cout << "sp1.use_count:  " << sp1.UseCount() << std::endl;
    	std::cout << "sp2.use_count:  " << sp2.UseCount() << std::endl;
    
    	SharedPtr<int> sp3(sp2);
    	std::cout << "sp1.use_count:  " << sp1.UseCount() << std::endl;
    	std::cout << "sp2.use_count:  " << sp2.UseCount() << std::endl;
    	std::cout << "sp3.use_count:  " << sp3.UseCount() << std::endl;
    
    	return 0;
    }

  • 相关阅读:
    OpenStack Paste.ini详解(二)
    OpenStack Paste.ini详解(一)
    PDB调试python代码常用命令
    Devstack 安装OpenStack Pike版本(单机环境)
    Openstack Pycharm 的远程调试
    django Forbidden
    Python 常用命令
    OSI模型和TCP/IP协议族(一)
    ubuntu 下关闭MySql server
    安装ubuntu时的注意事项----个人小总结
  • 原文地址:https://www.cnblogs.com/zyb993963526/p/16030558.html
Copyright © 2020-2023  润新知