Bade
Bade

Reputation: 709

Memory deallocation before reallocation

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

Answers (2)

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

Zan Lynx
Zan Lynx

Reputation: 54325

  • Old allocation is of the wrong size.
  • Old object might be shared with others, cannot be overwritten.
  • Old object is const
  • Old object contains references.

And there might be others.

Upvotes: 2

Related Questions