Do not create a container object containing auto_ptr, auto_ptr container

Source: Internet
Author: User

Do not create a container object containing auto_ptr, auto_ptr container
Zookeeper

When you copy an auto_ptr, the ownership of the object to which it points is handed over to the auto_ptr of the vertex, and it is set to NULL. In my understanding, copying an auto_ptr means changing its value. For example:

Auto_ptr <int> pint1 (new int); // pint1 points to an int

Auto_ptr <int> pint2 (pint1); // pint2 points to the pint1 int; pint1 is set to NULL

Pint1 = pint2; // now pint1 points to int again; pint2 is set to NULL

Let's look at a method to implement sort:

Template <class RandomAccessIterator, classCompare>

Void sort (RandomAccessIterator first, RandomAccessIteratorlast, Compare comp)

{

Typedeftypename iterator_traits <RandomAccessIterator >:: value_type ElementType;

RandomAccessIterator I;

... // Point I to the reference Element

ElementType effectvalue (* I); // copy the reference element to a local temporary variable.

...

}

Vector <auto_ptr <int> ints;

...

Sort (ints. begin (), ints. end (), greater ());

When we use iterator_traits <RandomAccessIterator>: value_type, we must add typename before it because it is a type name determined by template parameters. In this example, the parameter is RandomAccessIterator.

The statements with problems in the above Code are:

ElementType effectvalue (* I );

Because it copies an element from the sorted range to a temporary object. In our example, this element is an auto_ptr <int>, so this operation quietly sets the copied auto_ptr --- the one in the vector to NULL. More seriously, when the scope of tvalue ends, it will automatically delete the int that it points. Therefore, when sort is returned, the content in the vector has been changed and at least one int has been deleted.

Never create a container containing auto_ptr.


Differences between auto_ptr and delete

Template <class T>
Class auto_ptr {
Public:
Typedef T element_type;
Explicit auto_ptr (T * p = 0) throw ();
Auto_ptr (const auto_ptr <T> & rhs) throw ();
Auto_ptr <T> & operator = (auto_ptr <T> & rhs) throw ();
~ Auto_ptr ();
T & operator * () const throw ();
T * operator-> () const throw ();
T * get () const throw ();
T * release () const throw ();
};
This is the auto_ptr class. We can see that auto_ptr creates a Class Object. When this object disappears, it will automatically call the Destructor ~ Auto_ptr ();
Let's take a look ~ Auto_ptr (); function implementation:
~ Auto_ptr ()
{If (_ Owns)
Delete _ Ptr ;}
Delete is called here.
Therefore, they are different: auto_ptr creates an object, while new and delete are just functions! If you use auto_ptr, the memory overflow will not occur because you forget to delete it.

The following is a good article worth reading:
The most frequently used dynamic memory is in the code of C ++ applications. Programmers who have programming experience know that the use of the new operator must match the delete operator. In some cases, there may still be memory overflow. When an exception is thrown out, the normal control process of the program is changed, resulting in potential memory overflow. For example,
Void g () // may throw
{
If (some_condition = false)
Throw X ();
}
Void func ()
{
String * pstr = new string;
G (); // memory overflow if g throws an exception
Delete pstr; // The code line that cannot be reached if g throws an exception.
}
Int main ()
{
Try
{
Func ();
}
Catch (...)
{}
}

When g throws an exception, the exception handling mechanism expands the stack: g () exits, and controls the catch (...) code block that is transferred to main. In this case, the delete statement in func () will not be executed, resulting in pstr memory overflow. If a local automatic string variable is used instead of Dynamic Allocation-memory overflow will not occur:

String str; // a Local Automatic Object
G (); // no memory overflow
Many important data structures and applications, such as linked lists, STL containers, strings, database systems, and interactive applications, must use dynamic memory allocation. Therefore, they still risk memory overflow in case of exceptions. The C ++ Standardization Committee is aware of this vulnerability and adds a special class template to the standard library, which is std: auto_ptr, the objective is to facilitate smooth interaction between the dynamic memory and before an exception. Auto_ptr ensures that the allocated objects (that is, the objects allocated by the new operator) can be automatically destroyed and the memory can be automatically released when an exception occurs. Next we will discuss how to use auto_ptr correctly and effectively to avoid resource overflow when using dynamic memory. This technology applies to documents,... the remaining full text>

For auto_ptr

This problem is solved when the copy constructor and Operator = are implemented, that is, if the object is assigned a value by itself, this is returned, that is to say, in fact, your pp does not generate another auto_ptr, that is, p itself.

Your opinion is for those who design auto_ptr. It's okay to use it.

Auto_ptr (const auto_ptr <_ Ty> & _ Y) _ THROW0 ()
: _ Owns (_ Y. _ Owns), _ Ptr (_ Y. release ()){}
Auto_ptr <_ Ty> & operator = (const auto_ptr <_ Ty> & _ Y) _ THROW0 ()
{If (this! = & _ Y)
{If (_ Ptr! = _ Y. get ())
{If (_ Owns)
Delete _ Ptr;
_ Owns = _ Y. _ Owns ;}
Else if (_ Y. _ Owns)
_ Owns = true;
_ Ptr = _ Y. release ();}
Return (* this );}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.