Reprinted: The http://blog.sina.com.cn/s/blog_508938e10100f12x.htmlauto_ptr class can be used to manage a single object allocated by new, but cannot manage dynamically allocated arrays (we usually do not use arrays, but instead use vector instead of arrays ). Auto_ptr has unusual behavior when copying and assigning values, so auto_ptrs cannot be saved in STL containers. When auto_ptr leaves its own scope or is destroyed, the objects managed by auto_ptr will also be destroyed. Use the header file required by STD: auto_ptr: # include <memory> // Example 1 (B): security code, using auto_ptr
Void F ()
{
Auto_ptr <t> Pt (New T );.....
} // Cool: When Pt is out of scope, the Destructor is called, so that the object is automatically deleted and the current Code does not leak T-type objects, whether the function Exits normally or throws an exception, because the PT destructor will always be called at the time of exit. The cleanup is performed automatically.
Finally, using an auto_ptr is as easy as using a built-in pointer. If you want to "undo" the resource and use manual ownership again, you only need to call release (). // Example 2: Use an auto_ptr
Void g ()
{
T * pt1 = new t; // now, we have an allocated object.
Auto_ptr <t> auto_pt2 (pt1); // pass the ownership to an auto_ptr object. auto_pt2 points to pt1
// Use auto_ptr, just like we used simple pointers.
Auto_pt2 = 12; // It is like "* pt1 = 12 ;"
Auto_pt2-> somefunc (); // like "pt1-> somefunc ();" // get () to get the pointer Value
Assert (pt1 = auto_pt2.get (); // The same
// Use release () to revoke ownership. auto_pt2 gives the saved pointer address to pt3, and points itself to null.
T * pt3 = auto_pt2.release ();//
// Delete this object by yourself, because no auto_ptr has this object.
Delete pt3;
} // Pt2 no longer has any pointer, so do not try to delete it... OK. Do not delete it again. We can use the reset () function of auto_ptr to reset auto_ptr so that it has another object. If this auto_ptr already has an object, it will first Delete the existing object, so calling reset () is like destroying this auto_ptr, and then creating a new object and having a new object:
// Example 3: Use reset ()
//
Void H ()
{
Auto_ptr <t> Pt (New T (1 ));
PT. reset (New T (2); // that is, PT will first Delete the current address pointed to by Pt (the address obtained by new T (1 ), // then point to the address assigned by new T (2 ).
} // Finally, PT has a scope,
// The second t is also automatically deleted