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.