vendredi 27 juillet 2018

In the following example, from where does the pointer p gets the information?

vector& vector::operator = (const vector& a)
    //make this vector a copy of a
{
    double* p = new double [ a.sz ];   // allocate new space
    copy(a.elem, a.elem+a.sz, elem);     // copy elements
    delete[] elem;                     // deallocate old space
    elem = p;                         // now we can reset elem
    sz = a.sz;
    return *this;                     // return a self-reference
}

I thought that the third argument of std::copy() should be the pointer p, but the book (Programming principles and practice using C++ - 2nd edition) says:

"When implementing the assignment, you could consider simplifying the code by freeing the memory for the old elements before creating the copy, but it is usually a very good idea not to throw away information before you know that you can replace it. Also, if you did that, strange things would happen if you assigned a vector to itself" - Page 635 and 636.

So, the pointer elem must be third argument of std::copy() to not let the pointer be invalid for a moment. I think... But from where does p gets the information to be put in the array it points to, to be able to do: elem = p ?

Aucun commentaire:

Enregistrer un commentaire