1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
Once allocated, all arrays have fixed hi(array: fixed size) sizes.
There is no simple way to enlarge or shrink arrays. bf(C++) has no
ti(renew) operator. The basic steps to take when enlarging an array are the
following:
itemization(
it() Allocate a new block of memory of larger size;
it() Copy the old array content to the new array;
it() Delete the old array;
it() Let the pointer to the array point to the newly allocated array.
)
Static and local arrays cannot be resized. Resizing is only possible for
dynamically allocated arrays. Example:
verbinclude(-a examples/enlarge.cc)
The procedure to enlarge shown in the example also has several drawbacks.
itemization(
it() The new array requires tt(newsize) constructors to be called;
it() Having initialized the strings in the new array, tt(oldsize) of them
are immediately reassigned to the corresponding values in the original array;
it() All the objects in the old arrays are destroyed.
)
Depending on the context various solutions exist to improve the efficiency
of this rather inefficient procedure. An array of pointers could be used
(requiring only the pointers to be copied, no destruction, no superfluous
initialization) or raw memory in combination with the
link(placement new operator)(PLACEMENT) could be used (an array of objects
remains available, no destruction, no superfluous construction).
|