• 智能指针简单实现


    template <typename T>
    class SmartPointer {
    public:
        //构造函数
        explicit SmartPointer(T* p=0): _ptr(p), _reference_count(new size_t){
            if(p)
                *_reference_count = 1; 
            else
                *_reference_count = 0; 
        }
        //拷贝构造函数
        SmartPointer(const SmartPointer& src) {
            if(this!=&src) {
                _ptr = src._ptr;
                _reference_count = src._reference_count;
                (*_reference_count)++;
            }
        }
        //重载赋值操作符
        SmartPointer& operator=(const SmartPointer& src) {
            if(_ptr==src._ptr) {
                return *this;
            }
            releaseCount();
            _ptr = src._ptr;
            _reference_count = src._reference_count;
            (*_reference_count)++;
            return *this;
        }
     
        //重载操作符
        T& operator*() {
            if(ptr) {
                return *_ptr;
            }
            //throw exception
        }
        //重载操作符
        T* operator->() {
            if(ptr) {
                return _ptr;
            }
            //throw exception
        }
        //析构函数
        ~SmartPointer() {
            if (--(*_reference_count) == 0) {
                delete _ptr;
                delete _reference_count;
            }
        }
    private:
        T *_ptr;
            size_t *_reference_count;
            void releaseCount() {
            if(_ptr) {
                (*_reference_count)--;
                    if((*_reference_count)==0) {
                        delete _ptr;
                        delete _reference_count;
                    }
            }
            }
    };
     
    int main() 
    {
        SmartPointer<char> cp1(new char('a'));
        SmartPointer<char> cp2(cp1);
        SmartPointer<char> cp3;
        cp3 = cp2;
        cp3 = cp1;
        cp3 = cp3;
        SmartPointer<char> cp4(new char('b'));
        cp3 = cp4;
    }

     注意:

    构造函数、拷贝构造函数、赋值构造函数不同。

    构造函数时,会创建新的ref_count

    拷贝构造函数时,会获取拷贝对象的ref_count,然后+1

    赋值构造函数时,会先将自身的ref_count-1,调用一下release,然后再获取拷贝对象的ref_count,+1

  • 相关阅读:
    o9.17,习题
    09.17,二维数组,地图
    09.15,一维数组,冒泡排序
    09.11 小兔 成兔问题
    09.01,学习习题
    FTPHelper
    Wpf发送接收 win32消息
    win32Helper
    xml 封装类
    C# 多进程安全
  • 原文地址:https://www.cnblogs.com/zl1991/p/16003224.html
Copyright © 2020-2023  润新知