Smart pointer types in Rust include: Box: points to a value on the heap and automatically releases the object to prevent memory leaks. Rc: allows multiple pointers to point to the same heap object, and releases the object when the last pointer disappears. Arc: Similar to Rc, but supports multi-threaded concurrent access. RefCell: Provides mutable borrowing of immutable objects, ensuring that only one thread modifies the object at a time.
A smart pointer is a pointer to a dynamically allocated object that is used to manage its life cycle and prevent memory leaks. There are the following smart pointer types in Rust:
Box
let x = Box::new(5);
Rc
let x = Rc::new(5); let y = x.clone();
Arc
Rc
, but supports multi-threaded concurrent access. Arc
pointers can be safely shared between different threads. use std::sync::Arc; let x = Arc::new(5); let thread = std::thread::spawn(move || { println!("{}", x); });
RefCell
use std::cell::RefCell; let x = RefCell::new(5); let mut y = x.borrow_mut(); *y = 6;
Practical case: managing binary tree nodes
struct Node { value: i32, left: Option<Box<Node>>, right: Option<Box<Node>>, } impl Node { fn new(value: i32) -> Self { Self { value, left: None, right: None, } } fn insert(&mut self, value: i32) { if value < self.value { if let Some(ref mut left) = self.left { left.insert(value); } else { self.left = Some(Box::new(Node::new(value))); } } else { if let Some(ref mut right) = self.right { right.insert(value); } else { self.right = Some(Box::new(Node::new(value))); } } } } let mut root = Box::new(Node::new(10)); root.insert(5); root.insert(15);
In this example, Box
smart pointers are used to manage nodes, ensuring that Release them when the tree is destroyed.
The above is the detailed content of What are the types of smart pointers?. For more information, please follow other related articles on the PHP Chinese website!