C++ Logo

std-proposals

Advanced search

Re: Memory safety guarantees

From: Thomas Neumann <tneumann_at_[hidden]>
Date: Thu, 22 Apr 2021 22:15:55 +0200
> Consider
> auto it = std::as_const(v).end(); // let's just assume this is OK,
> and borrows the object
> v.insert(it, 42); // insert 42 at the end of the vector
> // here it'd be OK to say that `it` is "invalidated", but notice
> that from the compiler's POV `it` hasn't been destroyed
>
> or equivalently,
> v.insert(v.end(), 42);
>
> Your proposal will have to deal with this kind of code.
> This is a "corner case," but it's pretty far from the actual corner of
> the room. :)

this will not compile, of course. And correctly so. You cannot expect to
transfer the current C++ style unmodified to a borrow based interface.
This here would work:

v.insert(v.size(), 42)

which, incidentally, is also the way Rust handles inserts.

Note that I do not propose to change all existing STL classes or
something like this. I would just like to have a way to guarantee memory
safeties where the users as opted in to that mechanism (and is aware
that this requires some style changes).

Best

Thomas

Received on 2021-04-22 15:15:58