Array Design Idea

Craig Black cblack at ara.com
Mon Dec 10 11:04:15 PST 2007


I know that there has been discussion about the possibility of changing 
arrays to use two pointers insead of a pointer and a size.  Since this idea 
seems to be on the table, I though I would share another related idea.  I 
have written my own array template class in C++ a long while ago and I 
thought I would share my design because it has worked well for me and is 
quite efficient.

There are three things that need to be stored for a resizable array:  the 
pointer to the array, the size, and the capacity.  My array implementation, 
both the size and the capacity are stored on the heap with the array.  There 
is only one heap allocation, and the first 8 bytes are reserved for the size 
and capacity values.  Further, there is no heap allocation if the array is 
empty.  If the array is empty, then the pointer is null, and the array is 
assumed to have a size and capacity of zero, so there is no need to store 
the size or capacity of an empty array.

This means that an empty array is just a null pointer.  This is beneficial 
for my purposes because arrays are used a lot in my code, and about half of 
them end up being empty.  So storing an empty array efficiently is a good 
thing.  I have been using this system for a long time and haven't had any 
problems with it.

-Craig 





More information about the Digitalmars-d mailing list