Understanding Memory Management, Part 4: Rust Ownership and Borrowing by Curiositry
Posted by ekr on 31 Mar 2025
[Post updated 2025-04-20 to fix some minor errors flagged by Erik Taubeneck]
This is the fourth post in my planned multipart series on memory
management. Part I covers the basics of
memory allocation and how it works in C, and parts
II and III
covered the basics of C++ memory management, including RAII and smart
pointers. These tools do a lot to simplify memory management but because
they were added on to the older manual management core of C you’re
left with a system which is mostly safe if you hold it right
but which can quickly become unsafe if you’re not careful.
Next I want to talk about a language which was designed
to be safe from the ground up and won’t let you be unsafe:
Rust.
I’d originally planned to talk about garbage collected languages
next, but after all that time spent on how C++ works,
I decided it would work better to do Rust next and then
close with garbage collection.
Single Ownership #
Unlike C and C++—or any other language we’ll be looking
at—the basic design concept of Rust is single ownership. I.e.,
Any given object can only have a single owner.
We’ve already seen how to implement this model in C++ using
unique