Writing an assigment operator for a class...is this right?

I'm reading this book and I believe this to be an error, but considering the writer is obviously far more experienced than me I need someone who is also experienced to check for me.

We are writing the vector type as defined by the standard library.
This is what is defined in the book. The comments were added by me.

vector& vector::operator=(const vector& a)
// make this vector a copy of a
{
double* p = new double[a.sz]; // sz is what we are using to store our vector
// size.

copy(a.elem, a.elem+a.sz, elem); // std library copy algorithm
//elem is a pointer (array) that stores our elements

delete elem[] // do not allow a memory leak.

elem = p;

sz = a.sz // obviously our sizes are the same.

return *this;
}


when we call copy, shouldn't we use p as our destination and not elem? if we left it as it is, wouldn't we be deleting the elem we just assigned to and then setting the new elem to an empty array of a.sz size?
when we call copy, shouldn't we use p as our destination and not elem?

Yes.

It's in the errata:
http://www.stroustrup.com/Programming/PPP2errata.html
Last edited on
Topic archived. No new replies allowed.