4 ms·
Ask HN: Simple rules inspired by Rust ownership in C++?
Rust's ownership system is great.
Could we devise some simple rules and conventions inspired by Rust to have a safer resource/memory experience with C++ ?
Some pointers I gathered:
* A nice SO answer: http://stackoverflow.com/questions/30011603/how-to-enable-rust-ownership-paradigm-in-c/30062820#30062820
http://stackoverflow.com/a/30062820
* Stroustrup et al "Resource-Model" based on code static analysis: http://www.stroustrup.com/resource-model.pdf
* The idea of "Owner" hinting is nice, but requires tooling
- btrask 10y agoI'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.