• C++实现简单的智能指针


    /*
        智能指针的简单实现
    */
    
    template<typename T>
    class SamrtPtr
    {
    public:
        //构造函数
        SamrtPtr(T* ptr = nullptr) :m_ptr(ptr) {
            if (m_ptr) {
                m_count = new size_t(1);
            }
            else {
                m_count = new size_t(0);
            }
        }
    
        //拷贝构造函数
        SamrtPtr(const SamrtPtr&that)
        {
            if (this != &that) {
                this->m_ptr = that.m_ptr;
                //指针指向的实际上是同一个计数器,同一块内存
                this->m_count = that.m_count;
                (*this->m_count)++;
            }
        }
    
        //拷贝赋值函数
        SamrtPtr&operator=(const SamrtPtr&that)
        {
            //指针指向的实际上是同一个计数器,同一块内存
            if (this->m_ptr == that.m_ptr)
            {
                return *this;
            }
    
            if (this->m_ptr)
            {
                //将原来的引用计数减一
                (*this->_count)--;
                if (this->_count == 0) {
                    delete this->_ptr;
                    delete this->_count;
                }
            }
    
            this->m_ptr = that.m_ptr;
            this->m_count = that.m_count;
            (*this->m_count)++;
            return *this;
        }
    
        //重载*操作符
        T& operator*()
        {
            return *(this->m_ptr);
        }
    
        T *operator->()
        {
            return this->m_ptr;
        }
    
        ~SamrtPtr()
        {
            (*this->m_count)--;
            if (*this->m_count == 0)
            {
                delete this->m_ptr;
                delete this->m_count;
            }
        }
    
        size_t use_count() {
            return *this->m_count;
        }
    
    private:
        //指针
        T* m_ptr;
        //计数器
        size_t* m_count;
    };
  • 相关阅读:
    xtu数据结构 I. A Simple Tree Problem
    图论trainning-part-1 A. 最短路
    xtu数据结构 D. Necklace
    xtu数据结构 G. Count the Colors
    xtu数据结构 B. Get Many Persimmon Trees
    xtu数据结构 C. Ultra-QuickSort
    NYOJ 118 修路方案
    POJ 1679 The Unique MST
    NYOJ 115 城市平乱
    NYOJ 38 布线问题
  • 原文地址:https://www.cnblogs.com/LuckCoder/p/14549942.html
Copyright © 2020-2023  润新知