標籤: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