Rusty.hpp: A Borrow Checker and Memory Ownership System for C++20
Purpose and Nature of rusty.hpp
- Library provides a Rust-like borrow checker and ownership model for C++20, but enforced at runtime.
- Multiple commenters view it as an experiment or “can I do this?” project, not intended for production.
- The author confirms it’s exploratory, aimed at emulating Rust’s feel and testing styles, not a full compile‑time checker.
- Some see it mainly as an educational or “for fun/meme” tool rather than a practical solution.
Runtime vs Compile‑Time Borrow Checking
- Many find runtime checking less compelling; it resembles
std::unique_ptror Rust’sRefCell, adding indirections and checks instead of static guarantees. - Several posts argue C++ syntax and semantics don’t expose enough lifetime information to replicate Rust’s compile‑time borrow checker without compiler changes.
- Attempts via templates (including large industrial efforts) reportedly hit hard limits; some suggest you could build a DSL, but only for toy programs.
- Comparison with Nim and other languages: they can infer some lifetimes or use ownership-optimized reference counting, but often as performance optimizations, not strict safety like Rust.
C++ Type System and Standard Library Limitations
- Strong criticism of C++’s type system: difficult to express concepts like empty types (e.g., Rust’s
Infallible) and reason about them. - Discussion on
std::optionalvs Rust’sOption:std::optionallacks some ergonomic methods and pattern matching, and its operators can lead to UB if misused.- Rust’s
Optionis richer and integrates better with pattern matching and empty/unit types.
- Some argue modern C++ handles zero-sized types better, but legacy
stdAPIs lag behind and constrain design.
Rust vs C++ Ownership, Pointers, and Thread Safety
- Rust’s borrow checker is framed as a replacement for raw pointers, not for smart pointers; it enforces aliasing and mutation rules at compile time.
- Examples discussed:
- In C++, references can be invalidated by container mutations (e.g.,
vector::push_back) with no compiler warning. - In Rust, equivalent code simply does not compile because of lifetime and mutability rules.
- In C++, references can be invalidated by container mutations (e.g.,
- Rust distinguishes
Box/Rc/Arcand requires explicit interior mutability (Mutex,RefCell) to change shared data, tying intoSend/Syncfor thread safety. - C++ smart pointers (
unique_ptr,shared_ptr) don’t enforce these aliasing or thread-safety constraints; misuse remains easy.
Critiques of rusty.hpp Itself
- Some warn the library uses
RefCell-like runtime checks that are not thread-safe, yet examples show use withshared_ptr, potentially inviting UB in multithreaded code. - Lack of a clear non‑owning pointer concept is seen as another footgun in C++ context.
- Overall sentiment: interesting idea and proof‑of‑concept, but may introduce new hazards and overhead without delivering Rust-level safety.