feel auto_ptr still exist some insufficiency, efficiency is very low, and lost general pointer convenient commonly used operation, such as + +,--, etc., auto_ptr only overloaded =,*,-> these several operators, so use is very inconvenient.
One
Description: Int *a = Null;delete a;//do NothingThe destructor for this auto_ptr is this:~auto_ptr (){//Destroy the Objectdelete _myptr;}
second, there is a very important function in the auto_ptr release _ty *release () _throw0 (){//return wrapped pointer and give up ownership_ty *_tmp = _myptr;_myptr = 0;return (_tmp);}The function is to give its own pointer to the return value of release, while its own pointer means null
Three
the release function is called every time the copy is copiedauto_ptr<int> p1 (new int);After executing the following code, P1 will fail, p1=nullauto_ptr<int> P2 (p1); auto_ptr<int> P2 = p1;
This ensures that only one auto_ptr pointer points to each new pair image, thus avoiding duplicate delete,But one of the biggest drawbacks is that it doesn't fit the habit,If you use the original pointer after the assignment, it will cause a null pointer to crash.
personally, if you use reference counting, it might be better to delete a memory area when it is no longer pointed to by any pointers.
Encapsulates the pointer class as well as the pointer itself. So you need to overload, * and so on operators
template< class T>
Class My_auto_ptr
{
Private
t* m_ptr; Encapsulated pointer
Public
My_auto_ptr (t* P): M_ptr (P) {}
~my_auto_ptr () {delete m_ptr;}
t& operator* () {return *m_ptr;}
t* operator-> () {return m_ptr;}
}
Now, My_auto_ptr can be a lot more like pointers.
My_auto_ptr<int> MP (new Int (88)); Equivalent int* IP = new int (88);
int num = *MP; equivalent int num = *IP;
If there is such a class struct Arwen {void Test () {cout< "I am Arwen" <<;}
Then My_auto_ptr<arwen> MP (new Arwen); Equivalent arwen* IP = new Arwen;
Mp->test (); Equivalent Ip-test ();
3. Perfect version (copy construction)
A perfect point class often involves some manipulation of a copy construct. You can also make another smart pointer class as a constructor parameter, or assign a value to a class by =
template< class T>
Class My_auto_ptr
{
Private
t* m_ptr;
t* getptr () {//Used for construction assignment
t* tmp = m_ptr;
m_ptr = 0;
return TMP;
}
Public
Explicit My_auto_ptr (t* p = 0): m_ptr (P) {}
~my_auto_ptr () {delete m_ptr;}
t& operator* () {return *m_ptr;}
t* operator-> () {return m_ptr;}
My_auto_ptr (my_auto_ptr& MP)
{//copy constructor
M_ptr = MP. GetPtr (); After the MP is copied, its own original pointer is equivalent to invalid.
}
my_auto_ptr& operator= (my_auto_ptr& AP)
{//assignment operator
if (AP! = *this)
{
Delete m_ptr;
M_ptr = ap. GetPtr ();
}
return *this;
}
void Reset (t* p)
{//The pointer resets, which is equivalent to pointing the pointer to another place
if (P! = m_ptr)
Delete m_ptr;
M_ptr = p;
}
};
STL Smart Pointer auto_ptr