cppannotations/yo/memory/enlargearray.yo
Frank B. Brokken 6e0f21942b WIP on Memory
git-svn-id: https://cppannotations.svn.sourceforge.net/svnroot/cppannotations/trunk@279 f6dd340e-d3f9-0310-b409-bdd246841980
2009-10-30 15:54:20 +00:00

27 lines
1.4 KiB
Text

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 contents 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(memory/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 inefficent 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).