Member-only story

The title of this article can be “Exploring Smart Pointers in Rust: From Box to Custom Smart Pointers and Implicit Dereferencing”.

Beck Moulton
3 min readFeb 24, 2024

--

Smart pointers play a crucial role in Rust’s ownership system, providing more functionality than traditional pointers. Unlike pointers in C that are primarily used to reference memory locations, Rust’s smart pointers like Box<T>, Rc<T>, and RefCell<T> manage the lifetime of the data they hold. This management includes automatic memory deallocation and reference counting, ensuring memory safety without compromising efficiency.

Let’s consider the simplest smart pointer: Box<T>. Box<T> allows you to store values on the heap, which enables efficient moving of values to prevent deep copying. Moving a Box<T> means only copying the pointer, not the potential value. Let’s check how Rust dereferences a Box<T> just like a regular pointer.

fn main() {
// Value on the stack
let x = 10;
// Regular pointer to x
let x_ptr = &x;
// Dereferencing the pointer
println!("Value using regular pointer: {}", *x_ptr);

// Smart pointer (Box) pointing to an integer on the heap
let x = Box::new(10);
// Automatic dereferencing of the potential value
println!("Value using smart pointer: {}", *x);
}

Although Box<T> itself is a lightweight value containing metadata about its heap storage data, it mimics a regular pointer because it can be dereferenced using the dereference operator (*) to access the value it holds. That’s why types…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet