This is my first time posting here, so I appreciate any guidance on the style of my post.C++ has been progressively incorporating ideas from Rust to improve memory safety. Easy examples are std::expected which parallel Rust's Result, std::optional which parallels Rust's Option.I propose an adaptation of Rust's Box type: a pointer to a heap object that always contains a valid value and allows the templated object to be an incomplete type.
First of all, I have to acknowledge that this type will most definitely be a lot more restrictive than a std::unique_ptr.This container enforces two key invariants: (1) the internal pointer is never nullptr and always points to an initialized value, and (2) the contained value is immovable.To upkeep the invariant that the contained heap value is valid, if there is ever an invalid state,an exception would be thrown immediately.
Here's some of box's properties I've figured out so far (T being the template type):- As a more constrained unique_ptr, it would be implicitly movable to a unique_ptr.
- Move constructor swaps the internal pointers to not have to perform any extra initializations. Although this could be omitted from the standard and let implementations decide how to perform the move while keeping or discarding the invariant of the moved object. Either way should work well enough. I haven't yet thought about how up-casting and down-casting would function, but it shouldn't be too far from the way unique_ptr does that.
- To facilitate interoperation with C libraries, support forstd::inout_ptrcan be provided. std::inout_ptr would delete the object and set the pointer to nullptr in caseThis does risk breaking an invariant, but it would throw soon enough, and anyone who uses this would immediately assume this is the place where an invalid state is raised.