[Effective-cpp] Item 1: Uses and Abuses of vector

White Wolf wolof at freemail.hu
Wed Oct 27 12:06:36 EDT 2004


effective-cpp-bounces at accu.org wrote:
[SNIP]
>> I still did not see any proof that end() is calculated or that it is
>> actually cheaper to take end() out first.  But I have seen broken
>> code too many times, where end() was pre-evaluated and the vector
>> (later) changed inside the loop.  I find it a bit frustrating that
>> noone has addressed my question so far.  Since AFAIK end() is not
>> necessarily calculated, as well as even if it is it is inline, I
>> only see a disaster waiting to happen due to premature optimisation,
>> and no benefit whatsoever.
> 
> Strange, I've never had any bugs like that. Possibly because
> modifying a container while iterating over it is fraught
> withe danger that I've always been very careful with it, or just
> don't do it. 

You have missed that the subjective to that act of making the error and the
act of finding/fixing were two different people.  I do not have such bugs in
my own code either.  All in all what seems to be important to note is that
pre-fecthing end() is not necessarily an optimization and therefore should
not be done unless profiling the code suggests otherwise (which IMHO is
never).

BTW I have just realized that Pál's comment about pre-fetched end()
signalling an immutable container (as number of elements) in a loop also
could drag us into a discussion about the unfortunate mix-up between
immutable container vs. immutable elements.  Like container::erase() needs a
non-const iterator, while delete happily deletes objects pointed by a
pointer to const...

What this means for our current discussion is that even though updating the
elements inside a vector does not change the vector (as a container), we
cannot use a const reference to the vector, because that would only give us
const_iterator so we could not change the elements either...  Probably the
difference is not too clear, but I do think that Pál's convention shows that
there is a difference.

Attila aka WW






More information about the Effective-cpp mailing list