C++ 智能指针

#pragma once
#include 
using namespace std;
template 
class SmartPointer
{       
        public: 
                SmartPointer():mPointer(NULL){}
                SmartPointer(T* p):mPointer(p)
                {       
                        if(mPointer)
                                mPointer->incRefCount();
                }
                ~SmartPointer()
                {       
                        if(mPointer&&mPointer->decRefCount()==0)
                                delete mPointer;
                }
                SmartPointer(const SmartPointer& other):mPointer(other.mPointer)
                {       
                        if(mPointer)
                                mPointer->incRefCount();
                }
                SmartPointer& operator = (const SmartPointer& other)
                {       
                        T* temp(other.mPointer);
                        if(temp)
                                temp->incRefCount();
                        if(mPointer&&mPointer->decRefCount()==0)
                                delete mPointer;
                        mPointer = temp;
                        return *this;
                }
                
                T& operator*() const{return *mPointer;}
                T* operator->() const{return mPointer;}
                bool operator != (const T* o)const
                {       return mPointer!= o;    }
                bool operator != (const SmartPointer& o)const
                {       return mPointer!= o.mPointer; }
                bool operator == (const SmartPointer& o)const
                {       return mPointer == o.mPointer;  }
                bool operator ==(const T* o)const
                {       return mPointer!=o;     }
        
        private:
                T* mPointer;
};

class RefBase
{
        public:
                RefBase():mCount(0){}
                void incRefCount()
                {
             mCount++;
                }
                int decRefCount()
                {
                        return --mCount;
                }
                int getRefCount()const
                {
                        return mCount;
                }
                ~RefBase(){}
        private:
                int mCount;

};

 

你可能感兴趣的:(C++11)