Categories
Blog Code

Hypothetical Rust-ish Borrowing in C++

Last night I got into a insomniac code-spiral about replicating some of Rust’s borrowing warnings in C++. In place of Rust’s initial variable declararion of let I use wrapper Owner<T> in C++ that internally tracks ownership. Passing to another Owner<T> will take the ownership, or a Borrower<T> class can accept a properly owned value and reference it as a constant.

// Function borrowing a value can only read const ref
static void use(Borrower<int> v) {
  (void)*v;
}

// Function can mutate value via ownership which generates 'warnings' if used again incorrectly
static void use_mut(Owner<int> v) {
  *v = 5;
}

int main() {
  // Rather than just 'int', Owner<int> tracks the lifetime of the value
  Owner<int> x{3};

  // Borrowing value before mutating causes no problems
  use(x);

  // Mutating value passes ownership, has_been_moved set on original x
  use_mut(std::move(x));

  // Uncomment for owner_already_borrowed = 1
  //use(x);

  // Uncomment for owner_already_moved = 1
  //use_mut(std::move(x));

  // Uncomment for another owner_already_borrowed++
  //Borrower<int> y = x;

  //Uncomment for owner_use_after_move = 1;
  //return *x;
}