Do not create container objects containing auto_ptr

Source: Internet
Author: User
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.

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.