Class auto_ptr ://用于当异常发生时,产生的内存泄露,因为异常发生时,立即停止了某些函数 的执行,可能导致有些以前new的内存没有被delete。
in include <memory>
provided by the C++ standard library as a kind of a smart pointer that helps to avoid resource leaks when exceptions are thrown.//
Functions often operate in the following way,in Class auto_ptr;
1. Acquire some resources.//获取内存资源
2. Perform some operations.//使用内存资源
3. Free the acquired resources.//释放内存资源
The smart pointer can free the data to which it points
whenever the pointer itself gets destroyed. Furthermore, because the pointer is a local variable, it gets destroyed automatically when the function is exited regardless of whether the exit is normal or is due to an exception.
An auto_ptr is a pointer that serves as owner of the object to which it refers (if any). As a result,
an object gets destroyed automatically when its auto_ptr gets destroyed.//auto_ptr作为它所指对象的所有者,当auto_ptr释放的时候,对象也被释放。
A requirement of an auto_ptr is that its object has only one owner//auto_ptr要求对象只能有一个owner, 即一个对象只能有一个auto_ptr
Note that class auto_ptr<> does not allow you to initialize an object with an ordinary pointer by
using the assignment syntax. Thus, you must initialize the auto_ptr directly by using its value[5]//初始化时不能用赋值语句只能直接初始化
std::auto_ptr<ClassA> ptr1(new ClassA); //OK
std::auto_ptr<ClassA> ptr2 = new ClassA; //ERROR
auto_ptr所有权的转移:前一个auto_ptr失去对对象的所有权并且被赋予NULL指针,后一个auto_ptr获得对象的所有权(如果后一个auto_ptr已有对象,则先释放其所有权,再获取)
auto_ptr(p);p不能是指向array 的指针。
example1:
//initialize an auto_ptr with a new object
std::auto_ptr<ClassA> ptr1(new ClassA);
//copy the auto_ptr
//- transfers ownership from ptr1 to ptr2
std::auto_ptr<ClassA> ptr2(ptr1);:
example2:
//initialize an auto_ptr with a new object
std::auto_ptr<ClassA> ptr1(new ClassA);
std::auto_ptr<ClassA> ptr2; //create another auto_ptr
ptr2 = ptr1; //assign the auto_ptr
//- transfers ownership from ptr1 to ptr2
example 3:
//initialize an auto_ptr with a new object
std::auto_ptr<ClassA> ptr1(new ClassA);
//initialize another auto_ptr with a new object
std::auto_ptr<ClassA> ptr2(new ClassA);
ptr2 = ptr1; //assign the auto_ptr
//- delete object owned by ptr2
//- transfers ownership from ptr1 to ptr2
To assign a new value to an auto_ptr, this new value must be an auto_ptr. You can't
assign an ordinary pointer://普通的指针和auto_ptr不能相互赋值
std::auto_ptr<ClassA> ptr; //create an
auto_ptr
ptr = new ClassA; //ERROR
ptr = std::auto_ptr<ClassA>(new ClassA); //OK, delete old
object// and own new
Allowing an auto_ptr to pass by reference is very bad
design and you should always avoid it.//一定要避免将auto_ptr 作为引用参数传递。
const std::auto_ptr<int> p(new int);
std::auto_ptr<int> p;// p的值为NULL
const auto_ptr类似,const T *p; //p所指的对象内容可以更改但是,p不能更改。。。;而这里const auto_ptr指所有权将不会更改,而所指对象的data可以更改
因为auto_ptr的特点,使你可以不编写析构函数,但是一定要有copy construct 和operator =,。,它们都是可以转换所有权的。
如果auto_ptr一直都指向同一个东西 的话,那你可以考虑使用const auto_ptr;