What is Smart Pointer?
-
Same as C++ Smart,shared pointers, it allocates memory and deallocates when all references to it goes out of scope. They only point to 1 value. Examples: vec<T>, String.
Smart pointers are implemented using structs.
Examples
Rc<T> (Reference Counted Pointer)
-
Single-threaded Shared reference-counting pointers.
Rc
clone(): Invoking clone on Rc produces a new pointer to the same allocation in the heap. When the last Rc pointer to a given allocation is destroyed, the value stored in that allocation (often referred to as “inner value”) is also dropped
use std::rc::Rc;
struct Person {
name: String,
age: u8,
}
fn main() {
let person = Rc::new(Person {
name: String::from("Alice"),
age: 25,
});
println!("Name: {}", person.name); //Alice
println!("Age: {}", person.age); //25
let person_clone1 = person.clone();
let person_clone2 = person.clone();
println!("Number of owners: {}", Rc::strong_count(&person));
drop(person_clone2);
println!("Number of owners: {}", Rc::strong_count(&person));
drop(person_clone1);
println!("Number of owners: {}", Rc::strong_count(&person));
}
Features
- 1. Mutable Reference
If you need mutability, put a Cell or RefCell inside the Rc
- 2. Thread Safe (No)
Rc does not implement Send Trait
Rust compiler will check at compile time that you are not sending Rcs between threads.