Basically I would like to integrate a kind of borrow checker into C++
for data types that opt-in to that mechanism. For these types the
compiler enforces the invariant that you can have either one mutable
reference or arbitrary many immutable references to an object.
A straw man example could look like this:
class MyIntVector [[borrowchecker]] {
...
void push_back(int element);
[[borrows]] const_iterator begin() const;
};
void foo(MyIntVector&);
void bar() {
MyIntVector v;
v.push_back(1);
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. :)
–Arthur