现在的位置: 首页 > 综合 > 正文

auto_ptr的使用

2013年09月05日 ⁄ 综合 ⁄ 共 2559字 ⁄ 字号 评论关闭

#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指针是“传递”所有权,而普通指针是“共享”所有权。看下面例子:

std::auto_ptr<int> p1(new int(24));
std::auto_ptr<int> p2;
int *q1 = new int(12);
int *q2;
p2 = p1;
q2 = q1;
    经过两次赋值后,对于auto_ptr,p1为NULL,*p2为24;对于普通指针,*p1, *p2均为12。第一次赋值,p1把指向对象的所有权传递给了p2, p1不再拥有指向对象的所有权。而第二次赋值,q2和q1共享了对同一对象的所有权。因此,对于auto_ptr,一个对象只可能被一个智能指针指向,这样可有效避免内存泄漏问题。但是同时会引起新问题。看下面例子:
template<class T>
void BadPrint(std::auto_ptr<T> p)
{
    if (p.get() == NULL)
    {
         std::cout<<NULL;
    }
    else
    {
         std::cout<<*p;
    }
}
    然后我如下使用BadPrint函数:
std::auto_ptr<int> q(new int(18));
BadPrint(q);
*q = 12;
     该程序并未像我们所期望的一样:*q的值为12,而是会出现runtime error,why?因为我们把q作为函数参数传给了BadPrint,因此传递完成后q不再拥有对指向对象的所有权,而函数内部的局部变量p会接管q所指向对象的所有权,当函数执行完毕退出时,p的生命期截止同时delete所指向对象。因此q实际变为NULL,所以出错。如何避免出错?使用auto_ptr的引用?即 void BadPrint(std::auto_ptr<T> &p)。这是相当糟糕的一种做法。对智能指针使用引用混淆了所有权的问题。它导致所有权有可能被传递了,也可能没有被传递。无论如何应当避免对auto_ptr使用引用。
     可见智能指针并非对任何情况都智能。使用auto_ptr要知道:
1. 智能指针不能共享指向对象的所有权
2. 智能指针不能指向数组。因为其实现中调用的是delete而非delete[]
3. 智能指针不是万能的
4. 智能指针不能作为容器类的元素。例如:
template<class T>
void container::insert(const T &value)
{
   ..........
   X = value;
   ..........
}
事实上在stl中,所有的container要内部拷贝所传参数的值时都是传的const类型的值。因此无法用auto_ptr传进去。
、、、、、、、、、、、、、、、、、、、、、
一句话: //一句话,假定有一个动态分配的int空间,则在一个时刻只能有一个auto_ptr指针指向他!
这就是所有权的独占性

抱歉!评论已关闭.