• 智能指针模板,要管理动态分配的内存


    #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*/

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

  • 相关阅读:
    docker镜像管理基础
    docker的基础应用
    mysql基础
    策略模式
    简单工厂模式
    hystrix-go简介
    手把手带你使用 go-kit(option)
    手把手带你使用 go-kit(组件扩充,服务发现)
    手把手带你使用 go-kit(客户端直连)
    手把手带你使用 go-kit(基础篇)
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4913295.html
Copyright © 2020-2023  润新知