哈你路亚 發表於 2025-9-24 11:51:50

Rust 智能指针的使用详解

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>一、Rust 智能指针详解</li><ul class="second_class_ul"><li>1、Box&lt;T&gt;:堆内存分配</li><li>2、Rc&lt;T&gt;:引用计数指针</li><li>3、RefCell&lt;T&gt;:内部可变性</li><li>4、Arc&lt;T&gt;:原子引用计数</li><li>5、Mutex&lt;T&gt;与RwLock&lt;T&gt;:线程同步</li><li>6、Weak&lt;T&gt;:解决循环引用</li><li>7、组合模式</li><li>8、对比总结</li></ul><li>二、Rust 智能指针示例</li><ul class="second_class_ul"></ul></ul></div><p class="maodian"></p><h2>一、Rust 智能指针详解</h2>
<p>智能指针是Rust中管理内存和所有权的核心工具,通过封装指针并添加元数据(如引用计数)来实现安全的内存管理。以下是主要类型及其原理、使用场景和示例:</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202509/2025092411490535.png" /></p>
<p class="maodian"></p><h3>1、Box&lt;T&gt;:堆内存分配</h3>
<ul><li><strong>原理</strong>:在堆上分配内存,栈中存储指向堆的指针。所有权唯一,离开作用域时自动释放内存。</li><li><strong>使用场景</strong>:<ul><li>编译时未知大小的类型(如递归类型)</li><li>转移大数据所有权避免拷贝</li><li>特质对象(Trait Object)的动态分发</li></ul></li><li><strong>示例</strong>:<div class="jb51code"><pre class="brush:plain;">fn main() {
    let b = Box::new(5); // 在堆上存储整数5
    println!("b = {}", b); // 输出: b = 5
} // 离开作用域,堆内存自动释放
</pre></div></li></ul>
<p class="maodian"></p><h3>2、Rc&lt;T&gt;:引用计数指针</h3>
<ul><li><strong>原理</strong>:通过引用计数跟踪值的所有者数量。当计数归零时自动释放内存。<strong>仅适用于单线程</strong>。</li><li><strong>使用场景</strong>:多个部分只读共享数据(如图结构、共享配置)。</li><li><strong>示例</strong>:<div class="jb51code"><pre class="brush:plain;">use std::rc::Rc;
fn main() {
    let a = Rc::new(10);
    let b = Rc::clone(&amp;a); // 引用计数+1
    println!("Count: {}", Rc::strong_count(&amp;a)); // 输出: Count: 2
} // 离开作用域,计数归零,内存释放
</pre></div></li></ul>
<p class="maodian"></p><h3>3、RefCell&lt;T&gt;:内部可变性</h3>
<ul><li><strong>原理</strong>:在运行时检查借用规则(而非编译时),允许通过不可变引用修改内部数据。使用<code>borrow()</code>和<code>borrow_mut()</code>访问。</li><li><strong>使用场景</strong>:需要修改只读共享数据时(如缓存更新)。</li><li><strong>示例</strong>:<div class="jb51code"><pre class="brush:plain;">use std::cell::RefCell;
fn main() {
    let c = RefCell::new(42);
    *c.borrow_mut() += 1; // 运行时借用检查
    println!("c = {}", c.borrow()); // 输出: c = 43
}
</pre></div></li></ul>
<p class="maodian"></p><h3>4、Arc&lt;T&gt;:原子引用计数</h3>
<ul><li><strong>原理</strong>:类似<code>Rc&lt;T&gt;</code>,但使用原子操作保证线程安全。性能略低于<code>Rc</code>。</li><li><strong>使用场景</strong>:多线程共享数据(需配合<code>Mutex</code>)。</li><li><strong>示例</strong>:<div class="jb51code"><pre class="brush:plain;">use std::sync::Arc;
use std::thread;
fn main() {
    let val = Arc::new(100);
    let handle = thread::spawn(move || {
      println!("Thread: {}", val); // 安全共享
    });
    handle.join().unwrap();
}
</pre></div></li></ul>
<p class="maodian"></p><h3>5、Mutex&lt;T&gt;与RwLock&lt;T&gt;:线程同步</h3>
<ul><li><strong><code>Mutex&lt;T&gt;</code></strong>:互斥锁,一次仅允许一个线程访问数据。
<div class="jb51code"><pre class="brush:plain;">use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];
    for _ in 0..10 {
      let c = Arc::clone(&amp;counter);
      let handle = thread::spawn(move || {
            let mut num = c.lock().unwrap();
            *num += 1; // 修改受保护数据
      });
      handles.push(handle);
    }
    for handle in handles { handle.join().unwrap(); }
    println!("Result: {}", *counter.lock().unwrap()); // 输出: Result: 10
}
</pre></div></li><li><strong><code>RwLock&lt;T&gt;</code></strong>:读写锁,允许多个读取或单个写入。<div class="jb51code"><pre class="brush:plain;">use std::sync::RwLock;
let lock = RwLock::new(5);
{
    let r1 = lock.read().unwrap(); // 多个读取并发
    let r2 = lock.read().unwrap();
}
{
    let mut w = lock.write().unwrap(); // 独占写入
    *w += 1;
}
</pre></div></li></ul>
<p class="maodian"></p><h3>6、Weak&lt;T&gt;:解决循环引用</h3>
<ul><li><strong>原理</strong>:Weak 是 Rc 的非拥有智能指针,它不增加引用计数。</li><li><strong>使用场景</strong>:用于解决循环引用问题</li><li><strong>示例</strong>:<div class="jb51code"><pre class="brush:plain;">use std::rc::{Rc, Weak};
use std::cell::RefCell;

// 定义节点结构
struct Node {
    value: i32,
    parent: RefCell&lt;Weak&lt;Node&gt;&gt;, // 使用 Weak 避免循环引用
    children: RefCell&lt;Vec&lt;Rc&lt;Node&gt;&gt;&gt;, // 子节点使用 Rc
}

fn main() {
    // 创建叶子节点
    let leaf = Rc::new(Node {
      value: 3,
      parent: RefCell::new(Weak::new()),
      children: RefCell::new(vec![]),
    });

    // 创建分支节点,并设置 leaf 为其子节点
    let branch = Rc::new(Node {
      value: 5,
      parent: RefCell::new(Weak::new()),
      children: RefCell::new(vec!),
    });

    // 设置 leaf 的父节点为 branch(使用 downgrade 创建弱引用)
    *leaf.parent.borrow_mut() = Rc::downgrade(&amp;branch);

    // 尝试升级 leaf 的父节点
    if let Some(parent) = leaf.parent.borrow().upgrade() {
      println!("Leaf 的父节点值: {}", parent.value); // 输出: Leaf 的父节点值: 5
    } else {
      println!("父节点已被释放");
    }

    // 当 branch 被丢弃时,leaf 的 parent 升级会失败
}

</pre></div></li></ul>
<p class="maodian"></p><h3>7、组合模式</h3>
<ul><li><code>Rc&lt;RefCell&lt;T&gt;&gt;</code>:单线程内共享可变数据。
<div class="jb51code"><pre class="brush:plain;">let shared_data = Rc::new(RefCell::new(vec!));
shared_data.borrow_mut().push(3); // 修改共享数据
</pre></div></li><li><code>Arc&lt;Mutex&lt;T&gt;&gt;</code>:多线程共享可变数据(最常见组合)。<div class="jb51code"><pre class="brush:plain;">let data = Arc::new(Mutex::new(0));
// 多线程修改数据(见上文Mutex示例)
</pre></div></li></ul>
<p class="maodian"></p><h3>8、对比总结</h3>
<table><thead><tr><th>类型</th><th>线程安全</th><th>可变性</th><th>适用场景</th></tr></thead><tbody><tr><td>Box&lt;T&gt;</td><td>❌</td><td>所有权唯一</td><td>堆分配、递归类型</td></tr><tr><td>Rc&lt;T&gt;</td><td>❌</td><td>不可变共享</td><td>单线程共享只读数据</td></tr><tr><td>RefCell&lt;T&gt;</td><td>❌</td><td>内部可变</td><td>单线程运行时借用检查</td></tr><tr><td>Arc&lt;T&gt;</td><td>✅</td><td>不可变共享</td><td>多线程共享只读数据</td></tr><tr><td>Mutex&lt;T&gt;</td><td>✅</td><td>线程安全可变</td><td>多线程互斥修改数据</td></tr><tr><td>RwLock&lt;T&gt;</td><td>✅</td><td>读写分离</td><td>读多写少场景</td></tr></tbody></table>
<p class="maodian"></p><h2>二、Rust 智能指针示例</h2>
<p>以下是一个复杂的 Rust 智能指针示例,结合了 <code>Rc</code>、<code>RefCell</code> 和自定义智能指针,模拟图形渲染场景中的资源管理:</p>
<div class="jb51code"><pre class="brush:plain;">use std::rc::{Rc, Weak};
use std::cell::RefCell;
use std::ops::Deref;

// 自定义智能指针:带引用计数的纹理资源
struct Texture {
    id: u32,
    data: Vec&lt;u8&gt;,
}

impl Texture {
    fn new(id: u32, size: usize) -&gt; Self {
      Texture {
            id,
            data: vec!,
      }
    }
}

// 自定义智能指针:TextureHandle
struct TextureHandle(Rc&lt;Texture&gt;);

impl TextureHandle {
    fn new(texture: Texture) -&gt; Self {
      TextureHandle(Rc::new(texture))
    }
   
    fn get_id(&amp;self) -&gt; u32 {
      self.0.id
    }
}

impl Deref for TextureHandle {
    type Target = Texture;
   
    fn deref(&amp;self) -&gt; &amp;Self::Target {
      &amp;self.0
    }
}

// 场景节点:支持父子关系
struct SceneNode {
    name: String,
    texture: Option&lt;TextureHandle&gt;,
    children: RefCell&lt;Vec&lt;Rc&lt;RefCell&lt;SceneNode&gt;&gt;&gt;&gt;,
    parent: RefCell&lt;Weak&lt;RefCell&lt;SceneNode&gt;&gt;&gt;,
}

impl SceneNode {
    fn new(name: &amp;str) -&gt; Rc&lt;RefCell&lt;Self&gt;&gt; {
      Rc::new(RefCell::new(SceneNode {
            name: name.to_string(),
            texture: None,
            children: RefCell::new(Vec::new()),
            parent: RefCell::new(Weak::new()),
      }))
    }
   
    fn add_child(parent: &amp;Rc&lt;RefCell&lt;SceneNode&gt;&gt;, child: &amp;Rc&lt;RefCell&lt;SceneNode&gt;&gt;) {
      child.borrow_mut().parent.replace(Rc::downgrade(parent));
      parent.borrow_mut().children.borrow_mut().push(Rc::clone(child));
    }
   
    fn set_texture(&amp;mut self, texture: TextureHandle) {
      self.texture = Some(texture);
    }
   
    fn print_tree(&amp;self, depth: usize) {
      let indent = "".repeat(depth);
      println!("{}{}", indent, self.name);
      if let Some(tex) = &amp;self.texture {
            println!("{}Texture ID: {}", indent, tex.get_id());
      }
      for child in self.children.borrow().iter() {
            child.borrow().print_tree(depth + 1);
      }
    }
}

fn main() {
    // 创建共享纹理资源
    let shared_texture = TextureHandle::new(Texture::new(101, 1024));
   
    // 创建场景节点
    let root = SceneNode::new("Root");
    let camera = SceneNode::new("Camera");
    let mesh1 = SceneNode::new("Mesh1");
    let mesh2 = SceneNode::new("Mesh2");
   
    // 设置纹理
    {
      let mut root_mut = root.borrow_mut();
      root_mut.set_texture(shared_texture);
    }
   
    // 构建场景层级
    SceneNode::add_child(&amp;root, &amp;camera);
    SceneNode::add_child(&amp;root, &amp;mesh1);
    SceneNode::add_child(&amp;mesh1, &amp;mesh2);
   
    // 打印场景树
    root.borrow().print_tree(0);
   
    // 验证引用计数
    println!("\nReference counts:");
    println!("Root strong: {}", Rc::strong_count(&amp;root));
    println!("Root weak: {}", Rc::weak_count(&amp;root));
}
</pre></div>
<p><strong>示例解析:</strong></p>
<ol><li><p><strong>自定义智能指针</strong> <code>TextureHandle</code></p>
<ul><li>包装 <code>Rc&lt;Texture&gt;</code> 实现资源共享</li><li>实现 <code>Deref</code> 获得透明访问</li><li>提供资源 ID 访问方法</li></ul></li><li><p><strong>场景图管理</strong> <code>SceneNode</code></p>
<ul><li>使用 <code>Rc&lt;RefCell&lt;SceneNode&gt;&gt;</code> 实现共享所有权和内部可变性</li><li>子节点列表:<code>RefCell&lt;Vec&lt;Rc&lt;...&gt;&gt;&gt;</code> 实现运行时可变借用</li><li>父节点:<code>RefCell&lt;Weak&lt;...&gt;&gt;</code> 避免循环引用</li></ul></li><li><p><strong>资源共享机制</strong></p>
<ul><li>纹理资源通过 <code>TextureHandle</code> 共享</li><li>节点树通过 <code>Rc</code> 共享所有权</li><li>使用 <code>Weak</code> 引用打破循环依赖</li></ul></li><li><p><strong>输出示例</strong>:</p></li></ol>
<div class="jb51code"><pre class="brush:plain;">Root
Texture ID: 101
Camera
Mesh1
    Mesh2

Reference counts:
Root strong: 1
Root weak: 2
PS G:\Learning\Rust\ttt&gt;
</pre></div>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202509/2025092411490467.png" /></p>
<p><strong>关键特性:</strong></p>
<ol><li>内存安全:自动管理资源释放</li><li>内部可变性:通过 <code>RefCell</code> 修改不可变引用</li><li>循环引用防护:<code>Weak</code> 指针避免内存泄漏</li><li>透明访问:通过 <code>Deref</code> 实现直接访问</li><li>运行时借用检查:<code>RefCell</code> 在运行时验证借用规则</li></ol>
<p>到此这篇关于Rust 智能指针的使用详解的文章就介绍到这了,更多相关Rust 智能指针内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!</p>
                           
                            <div class="art_xg">
                              <b>您可能感兴趣的文章:</b><ul><li>rust中智能指针的实现</li><li>解读Rust的Rc&lt;T&gt;:实现多所有权的智能指针方式</li><li>Rust之智能指针的用法</li><li>Rust&nbsp;智能指针实现方法</li><li>rust智能指针的具体使用</li><li>详解rust 自动化测试、迭代器与闭包、智能指针、无畏并发</li></ul>
                            </div>

                        </div>
                        <!--endmain-->
頁: [1]
查看完整版本: Rust 智能指针的使用详解