It is possible to remove one or several contiguous elements from any array. Deleting elements from an array may not automatically free up memory.
Elements can be removed from an array.
The following code fragment shows the deletion of the second TElement
object
from a CArrayFixFlat<class T>
array:
class TElement { public : TElement(); public : TBuf<4> iData; };
CArrayFixFlat<TElement>* fixflat; fixflat = new (ELeave) CArrayFixFlat<TElement>(3); ... ... // elements added to the array at some point ... fixflat->Delete(1);
To delete what are now the third and fourth elements from the array, i.e.
the two contiguous elements starting at position two, use Delete()
and
specify both the starting position and the number of elements:
fixflat->Delete(2,2);
Deleting elements from an array does not automatically compress the array buffer; the space allocated to the array buffer remains unchanged. This means that adding an element to a same length type array after deleting an element is guaranteed not to fail. However, this is not true for a variable length array and is only true for a packed array if the size of the new element is less than or equal to the size of the deleted element.
Excess space in the
array buffer can be removed using the Compress()
member function.
This reduces the capacity of the array. For a same length flat array, an attempt
to add an element after compression causes re-allocation of the flat buffer.
To compress the array:
fixflat->Compress();
All elements within
an array can be deleted using the Reset()
function. This
function also compresses the array. Compressing the array when it is empty
causes the memory allocated to the array buffer to be freed.
For an array of pointers
to CBase
derived objects (i.e. a CArrayPtrFlat
or
a CArrayPtrSeg
type array), some care should be taken when
deleting elements from the array. The following code fragment deletes the
last two elements from ptrflat
(a CArrayPtrFlat
array)
and deletes the objects that those elements point to:
TInt index; CElement* ptr; ... index = ptrflat->Count(); ... ptr = (*ptrflat)[--index]; ptrflat->Delete(index); delete ptr; ... ptr = ptrflat->At(--index); ptrflat->Delete(index); delete ptr;
In general, before the
elements of this kind of array are deleted, the CBase
derived
objects to which those elements point should be destroyed. If they are not
destroyed, then a separate copy of those elements (i.e. the pointers), must be
taken to avoid orphaning the CBase
derived objects on the
heap.