C++标准库之智能指针类auto_ptr

来源:互联网 发布:金融街国贸区别知乎 编辑:程序博客网 时间:2024/06/04 19:48

初学C++标准库,想通过写博客的方式监督自己,让自己对C++标准库的理解更加透彻。

一、智能指针类auto_ptr是什么

智能指针类auto_ptr是为解决异常发生时显示分配资源无法释放的问题。

正常情况下显示分配资源如:

void fuction(){int *i=new int;int *p=new int;}
随便写一函数,显示过程。当在调用fuction函数时,如果由于内存不足等情况发生异常,异常会抛出,然后释放对象(指针i.j)当不会释放指针所指向的内存空间,基于这样的机制,所以C++模板库设计了智能指针类auto_ptr。目的在于防止内存泄露。

ps.如果对C++的异常处理机制不够了解,可以查看《C++ PRIMER》第四版中异常处理部分。

在异常发生时智能指针类auto_ptr通过调用析构函数来释放内存。

二、auto_ptr的定义在哪里

根据侯捷老师的书中说明是在memory头文件中,其实不是这样的,auto_ptr类的定义就在auto_ptr.h头文件中。

它一般由其他使用auto_ptr类的头文件包括使用,而不是直接使用。

三、auto_ptr类中成员声明

template<typename T>class auto_ptr{    private:        T * ptr;    public:        typedef T element_type;        //复制构造函数        explicit        auto_ptr(element_type *p=0) throw();        auto_ptr(auto_ptr&p) throw();        template<typename T1>          auto_ptr(auto_ptr<T1>&p) throw();        //重载赋值操作符        auto_ptr&        operator=(auto_ptr& p) throw();        template <class T1>        auto_ptr& operator=(auto_ptr<T1>& p) throw();        //析构函数        ~auto_ptr()throw();        //重载* ->指针行为        element_type&        operator*() const throw();        element_type*        operator->() const throw();        //支持智能指针auto_ptr赋值与复制的成员函数        element_type*        get() const throw();        element_type*        release throw();        void reset(element_type *p=0) throw();};

基本上auto_ptr中声明就以上几大部分。

分别是数据成员,复制构造函数,重载赋值操作符,析构函数,重载* ->基本指针行为,以及支持以上操作的成员函数。

疑惑:成员模板


四、auto_ptr类中成员函数的实现

1.支持智能指针auto_ptr赋值与复制的成员函数。

get():返回类中指向对象的指针。

element_type * get() const throw () { return ptr}

函数作用,返回类中指向对象的指针。

release():使类中指针不指向任何对象,并返回原对象地址

element_type *release() throw ()

{    element_type *t=ptr;

     ptr=0;

     return t;

}

reset(element_type *p):将原来的对象释放,拥有新对象

void reset( element_type *p)

    if(p!=ptr){

    delete ptr;

    ptr=p;

}


2.复制构造函数

普通指针用于构造智能指针类

explicit

auto_ptr(element *p=0) throw() : ptr(p) { }

explict关键字的作用是禁止单参数构造函数用于自动类型转换,所以auto_ptr<int>  p=new int;这句是错误的。


同类型的智能指针用于构造智能指针类

auto_ptr(auto_ptr &p) throw (): ptr(p.release()) {}


不同类型的智能指针用于构造智能指针类

template <class U> autp_ptr(auto_ptr<U> &p) throw() :ptr(p.release() ){ }


3.重载赋值操作符

重载同类型的赋值操作符

auto_ptr&

operator =(auto_ptr &p) throw()

{  reset( p.release());

   return *this;

}


重载不同类型的赋值操作符

template <class U>

auto_ptr & operator=(auto_ptr <class U>&p)throw()

{ reset(p.release());

   return *this;

}


4.析构函数

~auto_ptr () throw() {delete ptr}


5.重载解引用操作与箭头操作符

重载解引用操作符

element_type&

operator *() throw()

{ return *ptr;}

重载箭头操作符

element_type *

operator->() throw()

{return ptr;}


智能指针类auto_ptr中主要的操作就是以上这些。

五、智能指针类auto_ptr的使用

关于智能指针类auto_ptr的使用以及auto_ptr_ref类的说明放到后面。


     



















































0 0
原创粉丝点击