C++ weak_ptr 实战:解决 shared_ptr 循环引用的关键

发布时间:2026/6/17 20:03:47

C++ weak_ptr 实战:解决 shared_ptr 循环引用的关键 一、开篇weak_ptr 不是 “智能指针”而是 “救星”如果你用shared_ptr遇到了循环引用导致的内存泄漏那么weak_ptr就是唯一的解决方案。它不是用来管理内存的而是作为shared_ptr的 “观察者”—— 不增加引用计数却能安全访问共享内存。二、weak_ptr 核心原理弱引用定义weak_ptr是shared_ptr的辅助类指向shared_ptr管理的内存但不增加引用计数核心能力观察共享内存的状态是否已释放转为shared_ptr后安全访问对象彻底解决shared_ptr的循环引用问题。三、weak_ptr 核心用法解决循环引用1. 修复循环引用问题图例#include iostream #include memory using namespace std; struct Child; struct Parent { std::weak_ptrChild child; Parent() { cout create Parent endl; } ~Parent() { cout destroy Parent endl; } void hi()const { cout hello Parent endl; } }; struct Child { std::weak_ptrParent parent; Child() { cout create Child endl; } ~Child() { cout destroy Child endl; } }; int main() { std::shared_ptrParent pa(new Parent()); std::shared_ptrChild pc(new Child()); pa-child pc; pc-parent pa; cout pa: pa.use_count() endl; cout pc: pc.use_count() endl; return 0;// 析构正常执行内存释放 }2. 安全访问对象lock () 方法int main() { std::weak_ptrInt pw; { std::shared_ptrInt pa(new Int(10));//11 pa-Print(); pw pa;//12 cout pw.use_count(): pw.use_count() endl; std::shared_ptrIntpb(pa);//22 cout pw.use_count(): pw.use_count() endl; }//析构 cout pw.use_count(): pw.use_count() endl;//01 std::shared_ptrInt pc; pc pw.lock();//不能直接将弱引用智能指针赋值给pc要用一个锁 //pc-Print();//空指针解引用程序崩溃 return 0; }lock()原子操作转为shared_ptr如果对象已释放则返回空weak_ptr本身不能直接访问对象必须转为shared_ptr。四、weak_ptr 适用场景仅这 2 个解决shared_ptr的循环引用唯一核心场景缓存场景比如缓存池存储weak_ptr避免缓存占用内存导致对象无法释放。五、weak_ptr 常见误区误区 1用 weak_ptr 管理内存weak_ptrPerson wp(new Person(李四, 25)); // 错误weak_ptr 不能直接接管裸指针原因weak_ptr必须依附于shared_ptr不能单独管理内存。误区 2lock () 后不检查是否为空std::shared_ptrInt pc; pc pw.lock();//不能直接将弱引用智能指针赋值给pc要用一个锁 pc-Print();崩溃pc 指向的对象已释放解决方案始终用if判断lock()的返回值。六、总结weak_ptr是shared_ptr的 “专属辅助工具”核心作用解决shared_ptr的循环引用问题不增加引用计数不管理内存仅作为 “观察者”必须通过lock()转为shared_ptr才能安全访问对象非必要不使用仅在解决循环引用时登场。

相关新闻