C++ Logo


Advanced search

Re: On "transparently replaceable" in std::vector operations

From: Giuseppe D'Angelo <giuseppe.dangelo_at_[hidden]>
Date: Fri, 30 Apr 2021 13:37:16 +0200

On 30/04/2021 01:56, Jason McKesson via Std-Discussion wrote:
> By inserting an object into a vector, you have conceptually changed
> the address of all of the objects past that one in the container.
> However, any pointers/references cannot themselves move to aim at the
> correct object. Therefore, such pointers/references should no longer
> be considered valid pointers/references to what they pointed
> to/referenced.
> Put simply, a pointer/reference to an element in a container is not,
> and should not be considered, a fancy index.

I never said that pointers/references/iterators should magically move.
In fact, I said that pointers would point to the element that ends up
being in the position they were pointing to.

You're basically arguing that "it is what it is" regarding the lack of
such a guarantee. That is, the mental model that `vector` to go with is
a mental model that invalidates pointers, even if:

* such invalidation is unenforceable (unlike iterators);
* such invalidation doesn't actually happen in any implementation (are
implementations allowed to have extra capacity on the left to optimize
prepend? That makes a mess out of capacity(), but maybe there's an
escape hatch/hat trick);
* such invalidation cannot even happen because of (new? old?) language
rules (unlike iterators, and due to a lack of an ad-hoc
`std::invalidate` facility) and therefore it's not usable in
optimizations, sanitizers, etc.;
* it costs precisely zero for an implementation provide the extra
guarantee (in fact, is it already "accidentally" offered today by all

I'm not sure if I'm 100% convinced. A `vector` isn't an arbitrary data
structure, it's a quite specific one, with clear operational semantics.
And although I do see the very strict analogy between iterators and
pointers, the latter could be seen as a "lower level" facility. In such
a model, the guarantee could be provided for the pointers, in a scenario
of "you should know what you're doing". On the other hand, iterators can
still be under the invalidation rules -- and, if you decide to enable
debug iterators, then these rules actually DO get enforced...

Thanks for the insights,
Giuseppe D'Angelo | giuseppe.dangelo_at_[hidden] | Senior Software Engineer
KDAB (France) S.A.S., a KDAB Group company
Tel. France +33 (0)4 90 84 08 53, http://www.kdab.com
KDAB - The Qt, C++ and OpenGL Experts

Received on 2021-04-30 06:37:23