James Kanze
11/8/2008 9:26:00 AM
On Nov 8, 1:42 am, "barcaroller" <barcarol...@music.net> wrote:
> "Victor Bazarov" <v.Abaza...@comAcast.net> wrote in message
> news:gf2jh4$5cm$1@news.datemas.de...
> > The vector will contain a dynamic array of 'string' objects.
> > The 'reserve' operation allocates the array capable of
> > containing future 'string' objects (which will be
> > constructed using 'placement new', most likely). Taking the
> > address of v[0] (which returns the reference to the very
> > first object in the inner array) will give you the starting
> > address of the inner array. What's there to [not]
> > understand? Now, you probably need to understand how
> > 'string' works, as well. Do you?
> If the vector "contains" the strings, then reserving ahead of
> time is not useful for optimization because the vector would
> still not know what the size of the strings are until they are
> actually inserted.
That depends on the implementation of std::string. The sizeof
(as opposed to the size of) an object is a compile time
constant; std::string needs an additional indirection to handle
variable length, but this is hidden in std::string; std::vector
doesn't no beans about it. And depending on the implementation,
it may not always have to do a deep copy, or it may not need the
extra indirection if the strings are short enough.
> If, however, the vector contains only pointers/references to
> the strings, reserve() would still not be useful.
Oh yes it is. Perhaps even more so. Increasing the capacity of
a vector means copying member objects. If std::string is
systematically doing a deep copy (most do, at least if the
strings are longer than a certain length), then copying will
mean allocating a new string, copying the data, then deleting
the old one. (It's things like this that motivated the entire
movable business in the next version of the standard.)
The most frequent reason for reserve(), however, is to ensure
the validity of iterators.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34