STL之auto_ptr

來源:互聯網
上載者:User

標籤:des   style   blog   color   io   ar   strong   for   div   

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.