std::shared_ptr的简单实现

#ifndef STD_SHAREDPTR_H
#define STD_SHAREDPTR_H
#include <stdint.h>
#include <algorithm>
using namespace std;
template<typename T>

class My_SharedPtr{

    My_SharedPtr():
        count_(new size_t),
        ptr_(nullptr){

    }

    My_SharedPtr(T* ptr):
        count_(new size_t),
        ptr_(ptr){
        *count_=1;
    }

    ~My_SharedPtr(){
        --(*count_);

        if(count_==0){
            delete ptr_;
            delete count_;
            ptr_=nullptr;
            count_=nullptr;
        }
    }

    My_SharedPtr(const My_SharedPtr& other){
        ptr_=other.ptr_;
        count_=other.count_;

        ++(*count_);
    }

    My_SharedPtr& operator=(const My_SharedPtr& other){
        ptr_=other.ptr_;
        count_=other.count_;

        ++(*count_);

        return *this;
    }

    My_SharedPtr(My_SharedPtr&& other):
        ptr_(other.ptr_),
        count_(other.count_){

        other.ptr_=nullptr;
        ++(*count_);
    }

    My_SharedPtr operator=(My_SharedPtr&& other){
        if(this!=&other){
            ptr_(other.ptr_),
            count_(other.count_){

            other.ptr_=nullptr;
            ++(*count_);
        }

            return *this;
    }
    }

        T& operator* (){
            return *ptr_;
        }

        T* operator-> (){
            return ptr_;
        }

        T* get(){
            return ptr_;
        }

        size_t use_count(){
            return *count_;
        }

        bool unique(){
            return *count_==1;
        }

        void Myswap(My_SharedPtr& other){
            swap(*this,other);
        }

private:

    size_t* count_;
    T* ptr_;

};

#endif // STD_SHAREDPTR_H

猜你喜欢

转载自blog.csdn.net/weixin_40825228/article/details/82885648