Rust 智能指针
核对 Rust 智能指针的资源管理机制及七大常见类型适用场景:Box<T>、Rc<T>、Arc<T>、RefCell<T>、Mutex<T>、RwLock<T> 与 Weak<T>,并验证引用计数与运行时借用检查。
学完这一章,你能够
- 核对 Rust 智能指针的资源管理机制及七大常见类型适用场景:Box<T>、Rc<T>、Arc<T>、RefCell<T>、Mutex<T>、RwLock<T> 与 Weak<T>,并验证引用计数与运行时借用检查。
智能指针定位与七类核心场景选型
智能指针(Smart Pointers)不仅封装底层指针地址,还携带所有权计数、借用状态或并发锁等元数据,通常通过实现 `Deref` 与 `Drop` 特性提供透明解引用与自动资源释放。标准库常见类型按职责各司其职:堆上独占分配用 `Box<T>`;单线程多所有者共享用 `Rc<T>`;跨线程安全共享用 `Arc<T>`;单线程内部可变性用 `RefCell<T>`;多线程独占互斥访问用 `Mutex<T>`;读多写少并发访问用 `RwLock<T>`;打破引用计数循环引用防内存泄漏则用非拥有指针 `Weak<T>`。
堆分配、引用计数与弱引用:Box / Rc / Arc / Weak
`Box::new(5)` 将值放入堆内存并在栈上保存定长指针,适合递归类型或大对象转移;`Rc::new(5)` 通过 `Rc::clone(&data)` 增加强引用计数,允许单线程内多个所有者共享只读数据,计数归零即自动释放;`Arc<T>`(Atomic Reference Counted)语义与 `Rc<T>` 相同,但采用原子指令维护计数,因此可在多线程间安全共享。若两个 `Rc` 节点互相强引用会导致计数永不归零而泄漏内存,应通过 `Rc::downgrade(&five)` 创建 `Weak<T>` 弱引用——它不增加强引用计数,访问前须调用 `upgrade()` 判断目标是否仍存活。
内部可变性与并发锁:RefCell / Mutex / RwLock
`RefCell<T>` 提供单线程“内部可变性”:即使外层引用不可变,也可经 `data.borrow_mut()` 获取可变借用并将 `*borrowed_data = 10`;其代价是将“单写或多读”借用检查从编译期推迟到运行时,一旦在活跃期发生冲突借用会立即 panic。在多线程环境下,则使用 `Mutex::new(5)` 经 `m.lock().unwrap()` 获取互斥守卫以保证同一时刻仅单线程独占访问,或使用 `RwLock::new(5)` 经 `lock.read().unwrap()` / `write()` 支持多读者并发与写者排他。
生命周期管理、Rc<Data> 综合案例与总结
智能指针将动态内存的释放绑定到作用域结束(RAII),并支持通过 `Drop` trait 自定义析构逻辑,从根源上杜绝野指针与遗忘释放。在完整 `Rc<Data>` 示例中,创建 `Rc::new(Data { value: 5 })` 后两次调用 `Rc::clone(&data)`,`Rc::strong_count(&data)` 精准变为 `3`,且 `data_clone1` 与 `data_clone2` 均指向同一份 `Data { value: 5 }`;当三份句柄全部离开作用域后强计数归零并自动回收。本站离线校验器完整验证了 `Box`/`Rc`(计数 3 -> 0 自动析构)/`Weak` 升级与失效、`RefCell` 冲突借用 panic、`Arc+Mutex` 5 线程并发更新以及 `RwLock` 读写互斥规则。
运行离线 Python 校验:Rust Box/Rc/Weak 计数析构、RefCell 运行时借用检查与 Mutex/RwLock
"""Offline Rust semantic verifier for Chapter 28: Smart Pointers (Box, Rc, Arc, Weak, RefCell, Mutex, RwLock, Drop)."""
import json
import threading
from typing import Any
class BorrowMutPanic(Exception):
pass
class BoxPtr:
"""Models Box<T>: single heap owner with deterministic Drop."""
def __init__(self, value: Any, drop_log: list[str] | None = None, label: str = "Box") -> None:
self.value = value
self._dropped = False
self._drop_log = drop_log
self._label = label
def drop(self) -> None:
if not self._dropped:
self._dropped = True
if self._drop_log is not None:
self._drop_log.append(f"drop:{self._label}({self.value})")
class _RcInner:
def __init__(self, value: Any, drop_log: list[str], label: str) -> None:
self.value: Any = value
self.strong = 1
self.weak = 0
self.dropped = False
self.drop_log = drop_log
self.label = label
class RcPtr:
"""Models Rc<T> with strong_count, weak_count, Rc::clone, Rc::downgrade, and Drop."""
def __init__(self, inner: _RcInner) -> None:
self._inner = inner
self._alive = True
@classmethod
def new(cls, value: Any, drop_log: list[str], label: str = "Rc") -> "RcPtr":
return cls(_RcInner(value, drop_log, label))
def clone_rc(self) -> "RcPtr":
assert self._alive
self._inner.strong += 1
return RcPtr(self._inner)
def downgrade(self) -> "WeakPtr":
assert self._alive
self._inner.weak += 1
return WeakPtr(self._inner)
@property
def strong_count(self) -> int:
return self._inner.strong
@property
def weak_count(self) -> int:
return self._inner.weak
@property
def value(self) -> Any:
return self._inner.value
def drop(self) -> None:
if self._alive:
self._alive = False
self._inner.strong -= 1
if self._inner.strong == 0 and not self._inner.dropped:
self._inner.dropped = True
self._inner.drop_log.append(f"drop:{self._inner.label}({self._inner.value})")
self._inner.value = None
class WeakPtr:
def __init__(self, inner: _RcInner) -> None:
self._inner = inner
def upgrade(self) -> RcPtr | None:
if self._inner.strong == 0 or self._inner.dropped:
return None
self._inner.strong += 1
return RcPtr(self._inner)
class RefCell:
"""Models RefCell<T> runtime borrow checker (many readers OR single writer)."""
def __init__(self, value: Any) -> None:
self._value = value
self._shared = 0
self._mut_active = False
def borrow(self) -> tuple[Any, callable]:
if self._mut_active:
raise BorrowMutPanic("already mutably borrowed: BorrowError")
self._shared += 1
def release() -> None:
self._shared -= 1
return self._value, release
def borrow_mut(self) -> tuple[list[Any], callable]:
if self._mut_active or self._shared > 0:
raise BorrowMutPanic("already borrowed: BorrowMutError")
self._mut_active = True
cell = [self._value]
def release() -> None:
self._value = cell[0]
self._mut_active = False
return cell, release
class RwLockModel:
"""Models RwLock<T>: allows concurrent read guards, rejects write while readers hold lock."""
def __init__(self, value: Any) -> None:
self._value = value
self._readers = 0
self._writer = False
def try_read(self) -> tuple[bool, Any]:
if self._writer:
return False, None
self._readers += 1
return True, self._value
def release_read(self) -> None:
self._readers -= 1
def try_write(self, new_val: Any) -> bool:
if self._writer or self._readers > 0:
return False
self._writer = True
self._value = new_val
self._writer = False
return True
def run_cases() -> list[dict]:
cases = []
# Case 1: Box<T> heap allocation & deterministic Drop + Rc<Data> strong_count == 3 -> 0
drops: list[str] = []
b = BoxPtr(5, drops, "Box")
b_val = b.value
b.drop()
rc0 = RcPtr.new({"value": 5}, drops, "Data")
rc1 = rc0.clone_rc()
rc2 = rc0.clone_rc()
count_with_three = rc0.strong_count
weak = rc0.downgrade()
count_after_weak = (rc0.strong_count, rc0.weak_count)
upgraded_before = weak.upgrade() is not None
rc0.drop()
rc1.drop()
rc2.drop()
# Dropping the temporary upgraded Rc from above? We didn't drop it! Let's upgrade cleanly:
drops2: list[str] = []
five = RcPtr.new(5, drops2, "five")
weak_five = five.downgrade()
up_ok = weak_five.upgrade()
assert up_ok is not None
up_val = up_ok.value
up_ok.drop()
five.drop()
up_after_drop = weak_five.upgrade()
actual_1 = {
"box_value": b_val,
"rc_strong_count_3": count_with_three,
"weak_does_not_inc_strong": list(count_after_weak),
"weak_upgrade_before_drop": up_val,
"weak_upgrade_after_drop_is_none": up_after_drop is None,
"five_dropped_cleanly": drops2,
}
expected_1 = {
"box_value": 5,
"rc_strong_count_3": 3,
"weak_does_not_inc_strong": [3, 1],
"weak_upgrade_before_drop": 5,
"weak_upgrade_after_drop_is_none": True,
"five_dropped_cleanly": ["drop:five(5)"],
}
cases.append(dict(
name="box_rc_weak_and_drop_lifecycle",
summary="Verify Box::new(5), Rc::strong_count == 3, Weak downgrade/upgrade, and automatic Drop at count 0",
expected=expected_1,
actual=actual_1,
passed=actual_1 == expected_1,
))
# Case 2: RefCell<T> runtime interior mutability & conflicting borrow_mut panic
cell = RefCell(5)
guard, rel_mut = cell.borrow_mut()
guard[0] = 10
conflict_caught = False
try:
cell.borrow_mut()
except BorrowMutPanic:
conflict_caught = True
rel_mut()
val_after, rel_read = cell.borrow()
rel_read()
actual_2 = {
"mutated_value": val_after,
"double_borrow_mut_panicked": conflict_caught,
}
expected_2 = {
"mutated_value": 10,
"double_borrow_mut_panicked": True,
}
cases.append(dict(
name="refcell_runtime_borrow_check",
summary="Verify RefCell::borrow_mut mutates 5 -> 10 and panics on overlapping mutable borrow",
expected=expected_2,
actual=actual_2,
passed=actual_2 == expected_2,
))
# Case 3: Arc<Mutex<T>> thread-safe sharing + RwLock multi-reader / exclusive-writer rules
mu = threading.Lock()
shared = [5]
def add_one() -> None:
with mu:
shared[0] += 1
threads = [threading.Thread(target=add_one) for _ in range(5)]
for th in threads:
th.start()
for th in threads:
th.join()
rw = RwLockModel(5)
r1_ok, r1_val = rw.try_read()
r2_ok, r2_val = rw.try_read()
write_blocked_during_reads = not rw.try_write(99)
rw.release_read()
rw.release_read()
write_ok_after_reads = rw.try_write(99)
_, final_rw_val = rw.try_read()
rw.release_read()
actual_3 = {
"arc_mutex_final": shared[0],
"rwlock_two_concurrent_readers": [r1_ok, r2_ok, r1_val, r2_val],
"rwlock_write_blocked_with_readers": write_blocked_during_reads,
"rwlock_write_succeeded_after_release": write_ok_after_reads,
"rwlock_final_value": final_rw_val,
}
expected_3 = {
"arc_mutex_final": 10,
"rwlock_two_concurrent_readers": [True, True, 5, 5],
"rwlock_write_blocked_with_readers": True,
"rwlock_write_succeeded_after_release": True,
"rwlock_final_value": 99,
}
cases.append(dict(
name="arc_mutex_and_rwlock_concurrency",
summary="Verify Arc+Mutex 5-thread update (5 -> 10) and RwLock concurrent readers / exclusive writer",
expected=expected_3,
actual=actual_3,
passed=actual_3 == expected_3,
))
return cases
def main() -> None:
payload = {
"version": "CPython 3.12.14 offline Rust semantic verifier (rustc absent)",
"cases": run_cases(),
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对 Box(5)、Rc strong_count=3 与 Weak 释放后 upgrade=None、RefCell 重叠 borrow_mut panic、5 线程 Mutex=10 及 RwLock 读写排他。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:86ba6ae3182a40a8a2fe3ecb89481030c7fe0d93f0f742062b345dc9809290c7
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:104434831e9becd89d3e740c068e3bb18e52872a99e2a52c7a1a51944325c325
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
Rc<T> 与 Arc<T>、RefCell<T> 与 Mutex<T> 各自的核心适用边界是什么?为什么 Weak<T> 可以解决循环引用?
展开参考解答
Rc 与 RefCell 仅用于单线程(无原子/锁开销),多线程共享所有权与内部可变性须改用 Arc 与 Mutex/RwLock;Weak 不增加强引用计数(strong_count),只要所有强引用离开作用域计数即可归零释放资源,从而打破环状强引用泄漏。