Reputation: 709
I'm learning C++ and in book section about overloading operator =, it says: "we need to free the old space and assign new values to each data element". My question is: why we need to deallocate memory when it's going to be overwritten anyway? Why can't we simply increment pointers and write to same memory (and data will be of same size since we'll assigning object to an object of a same type)? EDIT: Code from a book:
template <class T>
Vec<T>& Vec<T>::operator=(const Vec& rhs)
{
// check for self-assignment
if (&rhs != this) {
// free the array in the left-hand side
uncreate();
// copy elements from the right-hand to the left-hand side
create(rhs.begin(), rhs.end());
}
return *this;
}
Upvotes: 0
Views: 133
Reputation: 40594
You are right, you could try to reuse the memory that's already allocated. That is even likely a good idea if the memory is a buffer that is usually larger than the data it holds (like in any good std::vector<>
implementation).
However, you cannot reuse the memory if the required size is larger than the buffer that's already allocated. That is, you would need to include the code to throw away the current allocation and replace it with a larger allocation in either case. Thus the memory reusing code is significantly more complex than the non-reusing code.
As such, unconditionally throwing away the old allocation and replacing it with a new allocation is an application of the KISS principle, and should always be the first implementation. If you find later that this operation is a bottleneck in your code, you can still go back and plug in an optimized implementation.
Upvotes: 1
Reputation: 54325
const
And there might be others.
Upvotes: 2