zoukankan      html  css  js  c++  java
  • 智能指针模板,要管理动态分配的内存

    #ifndef SMARTPTR_HPP
    #define SMARTPTR_HPP 
    #include <stddef.h>
    
    template <typename T>
    class SmartPtr{
        public:
            SmartPtr(T *type = NULL);
            void resetPtr(T *type);
            const T *getPtr()const;
            operator bool() const{
                return ptr_ == NULL;
            }
            ~SmartPtr();
    
            T &operator*();
            const T &operator*()const;
            T *operator->();
            const T *operator->()const;
    
        private:
            SmartPtr(const SmartPtr &);
            void operator=(const SmartPtr &);
            T *ptr_;
    };
    
    template <typename T>
    inline SmartPtr<T>::SmartPtr(T *type)
        :ptr_(type)
    {}
    
    template <typename T>
    inline void SmartPtr<T>::resetPtr(T *type)
    {
        if(ptr_ != type){
            if(ptr_ != NULL){
                delete ptr_;
            }
            ptr_ = type;
        }
    }
    
    template <typename T>
    inline const T *SmartPtr<T>::getPtr() const
    {
        return ptr_;
    }
    
    template <typename T>
    inline SmartPtr<T>::~SmartPtr()
    {
        if(ptr_ != NULL){
            delete ptr_;
        }
    }
    
    template <typename T>
    inline T &SmartPtr<T>::operator*()
    {
        return *ptr_;
    }
    
    template <typename T>
    inline const T &SmartPtr<T>::operator*() const
    {
        return *ptr_;
    }
    
    template <typename T>
    inline T *SmartPtr<T>::operator->()
    {
        return ptr_;
    }
    
    template <typename T>
    inline const T *SmartPtr<T>::operator->() const
    {
        return ptr_;
    }
    #endif  /*SMARTPTR_H*/

    版权声明:本文博主原创文章。博客,未经同意不得转载。

  • 相关阅读:
    Django模型层之ORM
    bzoj1037 [ZJOI2008]生日聚会
    bzoj4423 [AMPPZ2013]Bytehattan
    bzoj1018 [SHOI2008]堵塞的交通
    关于弦图一些问题的解法
    bzoj1006 [HNOI2008]神奇的国度
    bzoj2561 最小生成树
    bzoj3720 Gty的妹子树
    bzoj3489 A simple rmq problem
    bzoj4066 简单题
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4913295.html
Copyright © 2011-2022 走看看