C++ Logo


Advanced search

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

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Thu, 29 Apr 2021 19:56:58 -0400
On Thu, Apr 29, 2021 at 7:33 PM Giuseppe D'Angelo via Std-Discussion
<std-discussion_at_[hidden]> wrote:
> On 29/04/2021 23:17, Jason McKesson via Std-Discussion wrote:
> > And my point is that you don't need to*make* them invalid, precisely
> > because nobody can*detect* that they became invalid. User code isn't
> > allowed to use them, so you don't need to do anything. Neither do
> > `vector` implementations. You will find exactly zero code in
> > `std::vector` implementations that magically mark those pointers as
> > "invalid".
> >
> > They're invalid by convention, not by actual execution of something.
> <devil's advocate>
> If it's not because the compiler may take advantage of it, and it
> doesn't actually get checked by sanitizers, and what not: then why is
> there such a convention?
> Does it allow for some hypothetical extra leeway in `vector`
> implementations? Is it purely an historical artefact, maybe due to how
> `vector` was used to be implemented? Something else?
> From the sentence above, it seems to me that you agree with the fact
> that the straightforward implementation of `vector` will incur in no
> costs if it wanted to provide the guarantee that the pointers are valid.
> So why not providing the guarantee?
> </devil's advocate>

My very first post in this thread outlined the conceptual reasoning
for invalidating the pointers/references/iterators entirely distinct
from the question of whether the object model would allow for them to
remain valid.

It boils down to this: you have a pointer to an object, then you do
something to the container that conceptually does not manipulate that
object's value; therefore, the pointer either should point to the same
object with the same value or if that is not possible it should be

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

Put simply, a pointer/reference to an element in a container is not,
and should not be considered, a fancy index.

Received on 2021-04-29 18:57:12