Interesting reading, thanks!
From C to Single Ownership and Memory Safety without Borrow Checking, Reference Counting, or Garbage Collection
Submitted 1 year ago by sizeoftheuniverse@programming.dev to programming@programming.dev
Comments
XpeeN@sopuli.xyz 1 year ago
BestBunsInTown_@lemmy.world 1 year ago
This takes me back to freshmen CS class. I hoped to never look at pointers again but here we are
TehPers@beehaw.org 1 year ago
The idea of using single-ownership to track “reminder” objects is actually really cool, and a variation of it sees use in other languages too. Traditionally, RAII is used for resource acquisition and freeing (as the name implies), so smart pointers for example. However, it can also be used for things like mutexes to automatically free up a mutex when some kind of “guard” object is dropped (both Rust and C++ support this, and Rust even enforces it). It’s not the same as a “reminder” object, but instead of having the compiler tell you “you forgot to free the mutex”, you instead automatically get the mutex freed so you don’t need to explicitly do it anymore.
The article would be right that languages don’t traditionally enable some kind of “reminder” object in the sense that you can’t compile the code without first doing X with that object. However, from my experience, the RAII approach means you don’t need those reminder objects anyway since the action that you’re supposed to take when you’re done with some resource can be done automatically in these languages.
Here’s an example in Rust translating the ship/display cache example in the article to something that takes advantage of these “guards” to automatically notify the display cache when the ship is dropped. You’ll notice that in the
main
function, nowhere do I need to explicitly tell the display cache “hey this ship was destroyed”. Instead, the cache automatically knows and updates its state when theships()
method is called to get the list of ships in the cache. I believe something similar to this can be done in C++. C# would allow you to useIDisposable
and.Dispose()
to achieve something similar too, although it wouldn’t be an automatic process like in Rust and C++.