Smart Pointers
A pointer is a general concept for a variable contains an address in memory.
Smart pointers are data structures that not only act like a pointer but also have additional metadata and capabilities.
The concept of smart pointer is usually implemented by using structs. The characteristic that distinguishes smart pointers from ordinary structs is that smart pointers implement the Deref
and Drop
traits. The Deref
trait allows an instance of a smart pointer to behave like a reference so you can write code to work with either references or smart pointers. The Drop
trait allows you to customize the code that is run when an instance of the smart pointer goes out of its scope.
Using Box<T>
to Point to Data on the Heap
The Box<T>
type allows you to store data on the heap rather than on the stack.
Using Box<T>
to allocate memory on the heap
fn main() {
let b = Box::new(5);
}
When b
goes out of the scope, it will be deallocated at the end of main
, the deallocation happens for the box and the data it points to.
Treating Smart Pointers Like Regular References with the Deref
Trait.
Implementing the Deref
trait allows you to customize the behavior of the dereference operator, *
.
When we want to access the data that a pointer points to, we use the dereference operator *
to achieve it.
fn main() {
let x = 5;
let y = &x;
println("{}", *y);
}
Defining Our Own Smart Pointer
The Box<T>
type is ultimately defined as a tuple struct with one element.
So we'll define a smart pointer just like it.
struct MyPointer<T>(T);
impl<T> MyPointer<T> {
fn new(x: T) -> MyPointer<T> {
MyPointer(x)
}
}
Treating a Type Like a Reference by Implementing the Deref
Trait
use std::ops::Deref;
impl<T> Deref for MyPointer<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
By &self.0
the Deref
method returns a reference to the value we want to access with the *
operator.
Without the Deref
trait, the compiler can only dereference &
references. The deref
method gives the compiler the ability to make a value of any type that implements Deref
and call the deref
method to get a &
reference that it knows how to dereference.
Implicit Deref Coercions with Functions and Methods
Deref coercion is a convenience that Rust performs on arguments to functions and methods. It only works on types that implement the Deref
trait. Deref coercion happens automatically when we pass a reference whose type does not match the type of the argument to a function or a method.
How Deref Coercion Interacts with Mutability
Similar to how you use the Deref
trait to override the *
operator on immutable references, you can use the DerefMut
trait to override the *
operator on mutable references.
Rust does deref coercion when it finds types and trait implementations in three cases:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2020-02-13 c++ static用法
2020-02-13 操作系統3-內存管理(Linux內存管理)