首页 > 其他 > 详细

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

时间:2014-07-22 23:53:07      阅读:362      评论:0      收藏:0      [点我收藏+]
#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*/

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

原文:http://blog.csdn.net/nyist327/article/details/38051653

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!