Answer#
Rust frees memory deterministically, at a point you can read in the source. When a variable goes out of scope, the compiler inserts the code that destroys its value (the Drop trait). No background collector runs, there are no pauses, and the program does not carry a runtime for it.
Because every value has one owner, the compiler knows where each value ends. Moving a value to another variable or into a function moves the responsibility to free it with it. The output of this program shows the order, in the order the values are dropped:
struct Guard(&'static str);
impl Drop for Guard {
fn drop(&mut self) {
println!("freeing {}", self.0);
}
}
fn main() {
let _a = Guard("a");
{
let _b = Guard("b");
println!("inner scope ends");
}
let c = Guard("c");
drop(c);
println!("main ends");
}inner scope ends
freeing b
freeing c
main ends
freeing ab is freed at the closing brace of its block, c at the explicit drop(c), and a at the end of main. Memory held by a Vec, String or Box is freed the same way, and so are files, sockets and locks: Drop is the general "clean up when the owner is gone" mechanism, not only for memory.
How shared ownership works#
When several parts of a program really need to own the same value, wrap it in a reference-counted pointer. Rc is for one thread, Arc for values shared between threads. The value is freed when the last owner is dropped.
| Type | Threads | Cost | Frees the value |
|---|---|---|---|
Box<T> | one owner | one allocation | when the owner goes out of scope |
Rc<T> | single thread | a counter increment per clone | when the count reaches zero |
Arc<T> | many threads | an atomic counter increment per clone | when the count reaches zero |
use std::rc::Rc;
use std::sync::Arc;
use std::thread;
fn main() {
let shared = Rc::new(String::from("one owner or many"));
let other = Rc::clone(&shared);
println!("Rc count = {}", Rc::strong_count(&shared));
drop(other);
println!("Rc count = {}", Rc::strong_count(&shared));
let data = Arc::new(vec![1, 2, 3]);
let handle = {
let data = Arc::clone(&data);
thread::spawn(move || data.iter().sum::<i32>())
};
println!("sum from a thread = {}", handle.join().unwrap());
println!("Arc count = {}", Arc::strong_count(&data));
}Rc count = 2
Rc count = 1
sum from a thread = 6
Arc count = 1Common mistakes#
- Expecting
droporder to match C++ destructors in every case. Local variables are dropped in reverse order of declaration; the fields of a struct are dropped in the order they are declared. - Using
Rcwhen plain ownership or a reference would do. Reference counting is a tool for shared ownership, not the default. - Building a cycle of
Rcpointers. The counts never reach zero and the memory is never freed: see "Can a Rust program leak memory?".
Related questions#
Does Rust need a runtime?#
No runtime is needed for memory management. A program that uses async needs an executor, such as Tokio, which is a library you add, not part of the language.
What does drop(x) do?#
It takes ownership of x and lets it go out of scope immediately, so its Drop code runs at that line instead of at the end of the block.
Sources#
- The Rust Book, "Running Code on Cleanup with the Drop Trait": https://doc.rust-lang.org/book/ch15-03-drop.html
- The Rust Book, "Rc<T>, the Reference Counted Smart Pointer": https://doc.rust-lang.org/book/ch15-04-rc.html