Chapter 4. Ownership
I’ve found that Rust has forced me to learn many of the things that I was slowly learning as ‘good practice’ in C/C++ before I could even compile my code. ...I want to stress that Rust isn’t the kind of language you can learn in a couple days and just deal with the hard/technical/good-practice stuff later. You will be forced to learn strict safety immediately and it will probably feel uncomfortable at first. However in my own experience, this has led me towards feeling like compiling my code actually means something to me again.
Rust makes the following pair of promises, both essential to a safe systems programming language:
-
You decide the lifetime of each value in your program. Rust frees memory and other resources belonging to a value promptly, at a point under your control.
-
Even so, your program will never use a pointer to an object after it has been freed. Using a dangling pointer is a common mistake in C and C++: if you’re lucky, your program crashes. If you’re unlucky, your program has a security hole. Rust catches these mistakes at compile time.
C and C++ keep the first promise: you can call free or delete on any object in the dynamically allocated heap you like, whenever you like. But in exchange, the second promise is set aside: it is entirely your responsibility to ensure that no pointer to the value you freed is ever used. There’s ample empirical evidence that this is a difficult responsibility to meet: pointer misuse has ...