"more effective C + +" ITEM M9 He mentions auto_ptr. That is when the anomaly arises. How to release the heap memory allocated for an object and avoid writing memory release statements over and over again.
PS: In this book refers to the function exit problem, function exit will clean up the stack memory, regardless of how to exit gracefully or abnormally exit (only one exception is when you call longjmp. This drawback of Longjmp is the main reason for C + + leading support for exception handling). Based on this, we encapsulate the deletion of pointers into a stack object.
Such a function exit (exception or normal) invokes the destructor of the object, achieving our own intent to clean up the memory pointed to by the encapsulated pointer.
As a novice. Not very understanding, write down, learn to learn.
Ps:c++11 has not advocated the use of auto_ptr, please see link: http://www.cplusplus.com/reference/memory/auto_ptr/
Note: This class template is deprecated as of c++11. Unique_ptr is a new facility with a similar functionality, but with improved security (no fake copy assignments), Adde D Features (deleters) and support forarrays. See unique_ptr for additional information.
The following copy from: http://blog.sina.com.cn/s/blog_7708265a01010lyv.html
1. What is AUTO_PTR?
Auto_ptr is the class template provided by the C + + standard library, and the Auto_ptr object is the owner of this memory by initializing to the dynamic memory created by new. A piece of memory cannot be assigned to two owners at the same time.
When the Auto_ptr object life cycle ends, its destructor frees the dynamic memory owned by the Auto_ptr object itself. Even if an exception occurs. Dynamic memory can also be freed through the exception stack unwinding process. AUTO_PTR does not support the new array.
2. Auto_ptr need to include header files?
#include <memory>
3. How do I initialize a Auto_ptr object?
1) constructor function
1] Constructs an existing normal pointer to dynamic memory as a parameter
int* p = new int (33);
Auto_ptr<int> API (p);
2] Direct construction of smart pointers
auto_ptr< int > API (new int (33));
2) Copy Construction
Constructs a new smart pointer with an existing smart pointer
auto_ptr< string > Pstr_auto (New String ("Brontosaurus"));
auto_ptr< string > Pstr_auto2 (Pstr_auto); //using Pstr_auto to construct Pstr_auto2
Because a piece of dynamic memory intelligence is owned by a smart pointer, the process of ownership transfer occurs when a copy is constructed or assigned. During this copy construction, Pstr_auto loses all rights to the string memory, and Pstr_auto2 obtains it. When the object is destroyed, Pstr_auto2 is responsible for the active destruction of the memory.
3) Assign Value
Constructs a new smart pointer with an existing smart pointer
auto_ptr< int > p1 (new int (1024));
auto_ptr< int > p2 (new int (2048));
P1 = p2;
The object pointed to by P1 is deleted before the assignment. After the assignment, P1 has the full weight of the Int object.
The object value is 2048. P2 is no longer used to point to the object.
4. Does the empty auto_ptr need to be initialized?
The usual pointer does not point to whatever object when it is defined. We assign a value to it with NULL. For smart pointers. Because the constructor has a default value of 0. We are able to directly define empty auto_ptr such as the following:
auto_ptr< int > p_auto_int; //Do not point to whatever object
5. Prevent two Auto_ptr objects from owning the same object (one piece of memory)
Because the full power of auto_ptr is unique. So the following code can cause confusion.
int* p = new int (0);
Auto_ptr<int> AP1 (P);
Auto_ptr<int> AP2 (P);
Because AP1 and AP2 both feel that the pointer p is the tube. All attempts to remove p at the time of the destruction, the behavior of deleting the same object two times is undefined in the C + + standard. So we have to prevent such use of auto_ptr.
6. Beware of smart pointers as parameters!
1) when passed by value, a local object is generated in the function's scope during the function call to receive the incoming auto_ptr (copy construct), so that the passed-in Auto_ptr loses its entire right to the original object, which is deleted locally auto_ptr when the function exits.
For example, the following example:
void F (auto_ptr<int> AP)
{Cout<<*ap;}
Auto_ptr<int> AP1 (new int (0));
f (AP1);
cout<<*ap1; Error, after the F (AP1) function call, AP1 no longer has any objects.
2) when referencing or pointers, the above copy process does not exist. However, we do not know what to do with the incoming auto_ptr in the function, assuming that some of these operations have lost their full rights to the object, then this could lead to a fatal run-time error.
Conclusion: The const reference is the bottom line of the smart pointer as a parameter.
7. Auto_ptr cannot initialize to point to non-dynamic memory
The reason very easy,delete expressions are applied on pointers that are not dynamically allocated will result in undefined program behavior.
8. Auto_ptr frequently used member functions
1) Get ()
Returns the memory address of the object that auto_ptr points to. For example, the following example:
int* p = new int (33);
cout << "The Adress of P:" << p << Endl;
Auto_ptr<int> AP1 (P);
cout << "The Adress of Ap1:" << &ap1 << Endl;
cout << "The Adress of the object which AP1 point to:" << ap1.get () << Endl;
The output is as follows:
The Adress of p:00481e00
The Adress of ap1:0012ff68
The adress of the object which AP1 point to:00481e00
The first line is the same as the third row, which is the address of the memory where int resides.
The second line is the address of the memory where the class object itself is AP1.
2) Reset ()
Sets the object that auto_ptr points to again. Similar to an assignment operation, but the assignment action does not agree to assign a normal pointer to the AUTO_PTR directly, and reset () agrees. For example, the following example:
auto_ptr< string > Pstr_auto (New String ("Brontosaurus"));
Pstr_auto.reset (New string ("Long-neck"));
In the example, resetting the former Pstr_auto has the full right of "Brontosaurus" character memory. This memory will be released first. After that, Pstr_auto again has the full power of the "Long-neck" character memory.
Note: Reset (0) can release objects and destroy memory.
3) Release ()
Returns the memory address of the object that auto_ptr points to, and frees all rights to the object.
when initializing auto_ptr with this function, you can avoid the case that two Auto_ptr objects have the same object (compared to the Get function).
Examples include the following:
auto_ptr< string > Pstr_auto (New String ("Brontosaurus"));
auto_ptr< string > Pstr_auto2 (Pstr_auto.get ()); This is two auto_ptr have the same object
auto_ptr< string > Pstr_auto2 (Pstr_auto.release ()); Release can first free all rights
Attach the implementation code of the AUTO_PTR:
Namespace std{Template<class t> class Auto_ptr {private:t* ap; Public://constructor & destructor-----------------------------------(1) explicit auto_ptr (t* ptr = 0) throw (): AP (PTR) {} ~auto_ptr () throw () {delete AP; }//Copy & Assignment--------------------------------------------(2) auto_ptr (auto_ptr& rhs) throw (): AP (RH S.release ()) {} Template<class y> auto_ptr (auto_ptr<y>& rhs) throw (): AP (Rhs.release ()) {} auto_pt r& operator= (auto_ptr& rhs) throw () {Reset (Rhs.release ()); return *this; } template<class y> auto_ptr& operator= (auto_ptr<y>& rhs) throw () {Reset (Rhs.release ()); return *this; }//Dereference----------------------------------------------------(3) t& operator* () const throw () {return *a P } t* operator-> () const throw () {return AP; }//Helper functions------------------------------------------------(4)//value access t* get () consT throw () {return AP; }//Release ownership t* release () throw () {t* tmp (AP); AP = 0; return TMP; }//Reset value void Reset (t* ptr=0) throw () {if (AP! = ptr) {delete ap; AP = ptr; }}//Special conversions-----------------------------------------------(5) template<class y> struct AUTO_PTR_R EF {y* YP; Auto_ptr_ref (y* RHS): YP (RHS) {}}; Auto_ptr (auto_ptr_ref<t> RHS) throw (): AP (RHS.YP) {} auto_ptr& operator= (auto_ptr_ref<t> rhs) throw () {Reset (RHS.YP); return *this; } template<class y> operator auto_ptr_ref<y> () throw () {return auto_ptr_ref<y> (Release ()); } template<class y> operator auto_ptr<y> () throw () {return auto_ptr<y> (Release ()); } };}
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
"C + + smart pointer auto_ptr"