
Ask HN: Simple rules inspired by Rust ownership in C++? - netgusto
Rust&#x27;s ownership system is great.<p>Could we devise some simple rules and conventions <i>inspired</i> by Rust to have a safer resource&#x2F;memory experience with C++ ?<p>Some pointers I gathered:<p>* A nice SO answer: http:&#x2F;&#x2F;stackoverflow.com&#x2F;questions&#x2F;30011603&#x2F;how-to-enable-rust-ownership-paradigm-in-c&#x2F;30062820#30062820
http:&#x2F;&#x2F;stackoverflow.com&#x2F;a&#x2F;30062820
* Stroustrup et al &quot;Resource-Model&quot; based on code static analysis: http:&#x2F;&#x2F;www.stroustrup.com&#x2F;resource-model.pdf
    * The idea of &quot;Owner&quot; hinting is nice, but requires tooling
======
btrask
I've got a simple way of implementing Rust's borrow checker in C. It's based
on always nulling out old pointers rather than letting them dangle. Functions
that take ownership of an argument demand a pointer-to-pointer, and then null
out the caller's copy. When freeing memory which might've contained pointers,
I assert that the entire thing is zeroed, to ensure it doesn't have any
dangling pointers or leaks. Non-owning pointers are marked with const so they
can't be freed.

This obviously tracks ownership at runtime, rather than compile time, but
static analyzers are pretty good at tracking nulls, and optimizers minimize
the runtime performance impact. The end result is very similar to Rust, albeit
coming from the other direction.

At some point I'd like to write up a blog post with examples.

