本文共 1538 字,大约阅读时间需要 5 分钟。
auto_ptr类是一个类型形参的模版,它为动态分配的对象提供异常安全,它在头文件memory中定义。
如果通过常规指针分配内存,而且在执行delete之前发生异常,并且该异常不被局部捕获,就不会自动释放该内存。如果使用一个auto_ptr对象来代替,将会自动释放内存。在最常见的情况下,将auto_ptr对象初始化为由new表达式返回的对象的地址,例如:
int *p = new int(10);
auto_ptr<int> ap(p);
auto_ptr只能用于管理从new返回的一个对象,它不能管理动态分配的数组,而且当auto_ptr被复制或赋值的时候,将基础对象的所有权从auto_ptr对象转给副本,原来的auto_ptr对象重置为未绑定状态,所以不能将auto_ptr存储在标准库类型中。
注意:
1.
int *p = new int(10);
auto_ptr<int> ap1(p);
auto_ptr<int< ap2(p);
这样做是不可以的,因为ap1与ap2都认为指针p是归它管的,在析构时都试图删除p, 两次删除同一个对象的行为在C++标准中是未定义的。所以我们必须防止这样使用auto_ptr.。
2.int* pa = new int[10];
auto_ptr<int> ap(pa);
因为auto_ptr的析构函数中删除指针用的是delete,而不是delete [],所以我们不应该用auto_ptr来管理一个数组指针。
下面是auto_ptr的定义:
namespace std { templatestruct auto_ptr_ref {}; template class auto_ptr { public: typedef X element_type; // 20.4.5.1 construct/copy/destroy: explicit auto_ptr(X* p =0) throw(); auto_ptr(auto_ptr&) throw(); template auto_ptr(auto_ptr &) throw(); auto_ptr& operator=(auto_ptr&) throw(); template auto_ptr& operator=(auto_ptr &) throw(); auto_ptr& operator=(auto_ptr_ref ) throw(); ~auto_ptr() throw(); // 20.4.5.2 members: X& operator*() const throw(); X* operator->() const throw(); X* get() const throw(); X* release() throw(); void reset(X* p =0) throw(); // 20.4.5.3 conversions: auto_ptr(auto_ptr_ref ) throw(); template operator auto_ptr_ref () throw(); template operator auto_ptr () throw(); }; }
转载地址:http://bwklf.baihongyu.com/