#include <memory>
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
auto_ptr<int > api ,api2;
api = auto_ptr<int>( new int(10) );
cout<<"api:"<<*api<<endl;
/*
api对象的布局:一个int数表示该对象是否有效。(==1有效,==0无效)
一个指针 指向int数据(因为你在声明api时已经说了它时指向int的)
*/
api2 = api; //传递性:执行完本句之后,api无效,同时api2有效,api2的另一个字段指向int
auto_ptr<string > aps1,aps2;
aps1 = auto_ptr<string>(new string("pig") );
cout<<"aps1:"<<*aps1<<endl;
return 0;
}
vc6的说明:
auto_ptr
template<class T>
class auto_ptr {
public:
typedef T element_type;
explicit auto_ptr(T *p = 0) throw();
auto_ptr(const auto_ptr<T>& rhs) throw();
auto_ptr<T>& operator=(auto_ptr<T>& rhs) throw();
~auto_ptr();
T& operator*() const throw();
T *operator->() const throw();
T *get() const throw();
T *release() const throw();
};
The class describes an object that stores a pointer to an allocated object of type T
. The stored pointer must either be null or designate an object allocated by a new
expression. The object also stores an ownership indicator. An object constructed with a non-null pointer owns the pointer. It transfers ownership if its stored value is assigned to another object. The destructor for auto_ptr<T>
deletes the allocated object if it owns it. Hence, an object of class auto_ptr<T>
ensures that an allocated object is automatically deleted when control leaves a block, even via a thrown exception.
//好了,估计说了这么多 ,应该知道 auto_ptr的功能和不足了。
//再看看以下我 转过来的文章
STL中的auto_ptr指针是为了解决内存泄漏问题而设计的。它严格限制了指针拥有对指向对象的所有权。auto_ptr指针和普通指针的差别在于对指向对象所有权的处理不同。auto_ptr指针是“传递”所有权,而普通指针是“共享”所有权。看下面例子:
这就是所有权的独占性