| |
 | Improving Memory Reallocation with Vectors
By Danny Kalev, C++ Pro
|
Here's a familiar scenario: You store values in a buffer and have to adjust its size at runtime to accommodate more data. The traditional reallocation technique is tedious and error prone: in C, you call realloc() every time you need to enlarge the buffer and hope for the best. In simple-minded C++, things get worse; you don't even have a function that reallocates an array that was allocated by new. Not only do you have to reallocate it manually, you also have to copy the original data to the new destination and delete the previous array. In the following sections I will present a safe, simple, and automatic technique for memory reallocation in C++, namely using STL vectors.

When you store values in a buffer, you often have to adjust its size at runtime to accommodate more data. The traditional reallocation technique is tedious and error prone: you call realloc every time you need to enlarge the buffer and hope for the best. In simple-minded C++, things get worse; you don't even have a function that reallocates an array that was allocated by new. Not only do you have to reallocate it manually, you also have to copy the original data to the new destination and delete the previous array.

Instead of a built-in array, use an STL vector object to store incoming data it's safe, simple, and automatic.
|
|
Find Out More
The Open Group
A Modest STL Tutorial
10-Minute Solution:
Optimize Abstract Operations with Function Templates
Tech Tip: What's in an Allocator?
Tech Tip: What Happens When a Container Re-Allocates Itself?
 | TALK BACK |
During the C++ standardization process, the standards committee
considered eliminating built-in arrays altogether, replacing them with
vectors. Eventually, built-in arrays weren't removed from the language,
as we all know. Nevertheless, this suggestion is still raised
occasionally. Would you like to see vectors taking the
place of built-in arrays in C++ or do you prefer the current state of
affairs, namely the coexistence of built-in arrays and vectors? How
would such a change affect your legacy code and programming practices?
 |
|