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?
You are correct, and so is JeremyFriesner's comment, which points out that it should be:
std::copy(a.elem, a.elem.sz, p);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With