• 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;
    };
  • 相关阅读:
    Linux内核从原理到代码详解
    linux内核研究-8-块设备I/O层
    《Linux内核分析》课程总结
    Nginx 重写规则指南1
    Nginx初探
    Nginx源码分析:3张图看懂启动及进程工作原理
    nginx源码分析 +redis的那些事儿
    I/O 模型及其设计模式
    高并发性能调试经验分享
    myawr
  • 原文地址:https://www.cnblogs.com/LuckCoder/p/14549942.html
Copyright © 2020-2023  润新知