Moving, Not Copying, Elements during Reallocation

Image

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 strings

• 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 strings have valuelike behavior. When we copy a string, the new string and the original ...

Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.