大家都知道,C++使用new运算符分配的内存空间需要由程序员自己释放,而在编写代码过程中难免会有所遗漏。如果能使堆空间内存在离开作用域后自动释放就可以减轻大量的工作,做法就是将指针封装成对象,而这就是智能指针的作用,下面简要实现了对指针的封装:
//auto_ptr.h:declaration of auto_ptr
template <class T>
class auto_ptr{
public:
explicit auto_ptr(T *p = NULL);
template <class U>
auto_ptr(auto_ptr<U>& rhs); //拷贝构造函数模板使用任意兼容的智能指针初始化一个新的智能指针
~auto_ptr();
template <class U>
auto_ptr<T>& operator=(auto_ptr<U>& rhs); //赋值操作符模板允许从任意兼容智能指针赋值
T& operator*() const;
T* operator->() const;
T* get() const; //返回当前元素指针
T* release();
void reset(T *p = NULL);
private:
T *pointee;