I am reading the C++ Programming Language 4th Edition and I reached the section regarding Copy Assignment Constructors. The author has a class named Vector and he defines the copy assignment constructor like this
Vector& Vector::operator=(const Vector& a)
{
double* p = new double[a.sz];
for (int i=0; i != a.sz; ++i)
p[i] = a.elem[i];
delete[] elem;
elem = p;
sz = a.sz;
return *this
}
(For those who own the book, this can be found in page 74) Now, my question is: if p has a new resource, why isn't it released with a delete before the return? or said in another way: Why isn't the lack of a delete[] p considered a memory leak?
I ask this because, so far, I've noticed that for every new there must be a delete and the questions I've seen that say "Should I use delete here" state that for every new, there should be a delete. I saw this question Must new always be followed by delete? but in that case, the program finishes and the resource is released, while in the above code the program continues.
(Also, on a side question, would the elem = p statement call the copy-assignment constructor? this line confuses me because it seems like it would call it and do a sort of infinite loop)