欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

C++ 智能指针详解:unique_ptr, shared_ptr, weak_ptr

时间:2026年08月12日 05:34:29 浏览:1

C++ 智能指针详解:unique_ptr, shared_ptr, weak_ptr


智能指针是 RAII 的核心,自动管理动态内存,避免内存泄漏。


1. unique_ptr(独占所有权)



  • 不可拷贝,只可移动。

  • 适用于明确只有单个所有者的情况。


#include <memory>
std::unique_ptr<int> p1(new int(10));
std::unique_ptr<int> p2 = std::move(p1); // 转移所有权
// p1 现在为空

2. shared_ptr(共享所有权)



  • 引用计数,多个指针可指向同一对象。

  • 适用于共享资源。


std::shared_ptr<int> sp1 = std::make_shared<int>(20);
std::shared_ptr<int> sp2 = sp1; // 引用计数增加

3. weak_ptr(弱引用)



  • 不增加引用计数,用于打破循环引用。

  • 需要使用时转换为 shared_ptr。


class B;
class A { public: std::shared_ptr<B> b; };
class B { public: std::weak_ptr<A> a; }; // 使用 weak_ptr 避免循环

4. 最佳实践



  • 优先使用 std::make_uniquestd::make_shared

  • 避免裸指针管理动态内存。

  • 使用 weak_ptr 观察共享对象。