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 {
template <class Y> struct auto_ptr_ref {};
template <class X>
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 <class Y> auto_ptr(auto_ptr<Y>&) throw();
auto_ptr& operator=(auto_ptr&) throw();
template <class Y> auto_ptr& operator=(auto_ptr<Y>&) throw();
auto_ptr& operator=(auto_ptr_ref<X>) 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<X>) throw();
template <class Y> operator auto_ptr_ref<Y>() throw();
template <class Y> operator auto_ptr<Y>() throw();
};
}
本文详细介绍了C++标准库中的auto_ptr智能指针类。它能确保动态分配的对象在不再使用时得到正确释放,避免内存泄漏。文章还讨论了auto_ptr的一些限制,如不能管理动态数组及在复制或赋值时的所有权转移问题。

被折叠的 条评论
为什么被折叠?



