Re: std::vector<T>::insert()
Am 14.10.2012 04:27, schrieb Wil Evers:
Daniel Kr?gler wrote:
This is a defect of the library implementation. The insert function
does not impose any requirements upon the origin of the provided
value, so this can also be an existing element of the same
container. An implementation has to manage this internally: If the
container needs reallocation before the insert it needs to create a
copy first before doing the reallocation and internal data moves.
I disagree. If reallocation takes place, then insert() invalidates
all iterators and references to the vector; if no reallocation takes
place, then insert() only guarantees the validatity of the iterators
and references before the insertion point.
The effects that you are mentioning here are only descriptions of the
effects of the operation and do not effect pre-conditions on
arguments. If an operation really depends on special properties of
the arguments it needs to mention this (as constraints). For example,
the situation would have been different for a range insertion, e.g.
v.insert( v.begin(), v.begin(), v.end() );
Here the wording clearly says in the Sequence container requirements:
"pre: i and j are not iterators into a."
Therefore this kind of code violates a clear pre-condition and the
effects are undefined.
There are no similar constraints upon push_back, insert() with one
value_type argument, etc, therefore this has to be managed by an
implementation.
In both cases, the reference returned by v[0] is invalidated by a
call to insert at v.begin(); I don't think there's a requirement
that says that insert() should somehow postpone that invalidation
until the reference passed to it is read to supply the new element's
value.
Your conclusions are incorrect. It is completely irrelevant for the
function call whether one of the effects is the invalidation of a
(previous) function argument. Without extra wording an implementation
has to ensure that the use-case works. Typically, implementations use
non-portable tricks to validate whether a reference is not part of the
container. Note also that Visual Studio 2012 has fixed this
implementation defect.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]