|
|
The initial capacity of a string or array is the number of cells initially allocated to it. Initial capacity should not be confused with maximum size, which is the size at which G2++ truncates fixed size strings and arrays during input or output. Since a string or array can grow up to its initial capacity without reallocation, understanding initial capacity--and how to control it--is the key to writing efficient G2++ programs.
When a number N is used to declare the size of a string or array, the string or array will, in most cases, be created with an initial capacity of N elements. (There are cases where N is ignored insofar as initial capacity is concerned. These cases are discussed in the next section.)
When an asterisk is used, the string or array will be allocated with a default initial capacity of at least ten elements. Why not 100? Whatever number we chose for the default, it would not be right for some programs. We have therefore enhanced the asterisk notation to allow programmers to specify an explicit initial capacity for arbitrary size Strings and arrays.
* default initial capacity *(N) default initial capacity of N
To avoid reallocation entirely, always specify a value of N greater than the largest number of elements anticipated. Here's an example:
usr.g usr login *(11) id usr LONG grp SHORT name * proj *(100) LONG
As before, login, name and proj are arbitrary size strings and arrays, but login will have an initial capacity of at least 11 characters and proj will have an initial capacity of at least 100 longs. name has the default initial capacity of at least 10 characters. The following code is therefore guaranteed not to incur any runtime overhead due to reallocation:
#include "usr.h" USR u; ... u.login="hello world"; u.proj.reserve(99);