Before we write the reallocate
member, we should think a bit about what it must do. This function will
• Allocate memory for a new, larger array of string
s
• Construct the first part of that space to hold the existing elements
• Destroy the elements in the existing memory and deallocate that memory
Looking at this list of steps, we can see that reallocating a StrVec
entails copying each string
from the old StrVec
memory to the new. Although we don’t know the details of how string
is implemented, we do know that string
s have valuelike behavior. When we copy a string
, the new string
and the original string
are independent from each other. Changes made to the original don’t affect the copy, and vice versa.
Because string
s act like values, we can conclude that each string
must have its own copy of the characters that make up that string
. Copying a string
must allocate memory for those characters, and destroying a string
must free the memory used by that string
.
Copying a string
copies the data because ordinarily after we copy a string
, there are two users of that string
. However, when reallocate
copies the string
s in a StrVec
, there will be only one user of these string
s after the copy. As soon as we copy the elements from the old space to the new, we will immediately destroy the original string
s.
Copying the data in these string
s is unnecessary. Our StrVec
’s performance will be much better if we can avoid the overhead of allocating and deallocating the string
s themselves each time we reallocate.