Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a mistake in this code example in Stroustrup's "Programming Principles and Practices" book?

I came across this code example in chapter 18 of Stroustrup's "Programming Principles and Practices with c++ 2nd ed." Book.

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; 
 sz = a.sz;
 return *this; 
}

The above example seems suspect to me. Based on my understanding, I would expect the copy function to copy into p instead of elem. Is the code right or is my fundamental understanding of this concept faulty?

like image 606
Ademola Avatar asked Nov 14 '22 19:11

Ademola


1 Answers

You are correct, and so is JeremyFriesner's comment, which points out that it should be:

std::copy(a.elem, a.elem.sz, p);
like image 63
einpoklum Avatar answered Jan 10 '23 17:01

einpoklum