语言基础(23):智能指针

夙愿已清 提交于 2019-11-29 08:33:37

智能指针的使用栗子(如下定义中,也可以将指针计数维护类增加封装为友元类):

    // CMySmartPtr指针封装类,将普通指针封装为智能指针
    template <class T>
    class CMySmartPtr  
    {
    public:
        /* 构造函数 */
        CMySmartPtr(T* pT)
        {
            pCountT = new CCountT(pT);
        }
        
        CMySmartPtr()
        {
            pCountT = NULL; // 默认指针为空
        }
     
        /* 复制控制 */
        ~CMySmartPtr()
        {
            DeleteData();
        }
     
        CMySmartPtr(const CMySmartPtr& p)
        {
            CopyData(p);
        }
     
        CMySmartPtr& operator=(const CMySmartPtr& p) 
        {
            if (this != &p)   // 注意自身对自身赋值的情况
            {
                DeleteData();
                CopyData(p);
            }
     
            return *this;
        }
     
        /* 指针*和->解引用 */
        T& operator*()
        {
            return *(this->pCountT->pT);
        }
     
        T* operator->()
        {
            return this->pCountT->pT;
        }
     
    private:
        // 装饰类,为智能指针维护引用计数、和所管理类型的指针
        class CCountT
        {
        public:
            CCountT(T* pT)
            {
                this->pT = pT;
                this->nCount = 1;
            }
            ~CCountT()
            {
                delete pT;
            }
            T* pT;
            int nCount;
        };
     
        // 统一共享的指针,依靠引用计数来释放
    private:
        CCountT *pCountT;
     
        void CopyData(const CMySmartPtr& p)
        {
            p.pCountT->nCount++;
            this->pCountT = p.pCountT;
        }
     
        void DeleteData()
        {
            if (pCountT && --pCountT->nCount==0)
            {
     
                delete pCountT;
                pCountT = NULL;
            }
        }
    };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!