首页 > 代码库 > STL之auto_ptr

STL之auto_ptr

What‘s auto_ptr?

  The auto_ptr type is provided by the C++ standard library as a kind of a smart pointer that helps to avoid resource leaks when exceptions are thrown. Note that I wrote "a kind of a smart pointer." There are several useful smart pointer types. This class is smart with respect to only one certain kind of problem. For other kinds of problems, type auto_ptr does not help. So, be careful and read the following subsections.

 

Why need auto_ptr?

  C++中没有垃圾回收机制,需要程序员动态new和delete,这是不方便并且容易出现内存泄露等等问题的。例如:

  This function is a source of trouble. One obvious problem is that the deletion of the object might be forgotten (especially if you have return statements inside the function). There also is a not-so-obvious danger that an exception might occur. Such an exception would exit the function immediately without calling the delete statement at the end of the function. The result would be a memory leak or, more generally, a resource leak. 

  An auto_ptr is a pointer that serves as owner of the object to which it refers (if any).

  这有点类似于Qt的内存处理机制,在Qt中,凡是继承于QObject的类,如果给类的对象指定父类,那么该对象会随着父类的destroyed而destroyed。 

  As a result, an object gets destroyed automatically when its auto_ptr gets destroyed. A requirement of an auto_ptr is that its object has only one owner.

 

How to use auto_ptr?

 

//header file for auto_ptr    #include <memory>    void f()    {        //create and initialize an auto_ptr        std::auto_ptr<ClassA> ptr(new ClassA);        ...                           //perform some operations    }

 

  when we use auto_ptr, there is no need for delete statement any more.

  An auto_ptr has much the same interface as an ordinary pointer; that is, operator * dereferences the object to which it points, whereas operator -> provides access to a member if the object is a class or a structure.

  However, any pointer arithmetic (such as ++) is not defined (this might be an advantage, because pointer arithmetic is a source of trouble).

 

STL之auto_ptr