跳转到主要内容
模块 7 · 第 1 课(共 2)课程中的15/18~12 min
模块课程(1/2)

std::unique_ptr 和 std::shared_ptr

在经典 C++ 中,使用 new 和 delete 运算符进行手动内存管理是错误的常见来源,例如内存泄漏(资源从未释放)或悬空指针(指向已释放内存的指针)。

现代 C++ 引入了智能指针,在 <memory> 标头中定义。它们使用 RAII(资源获取即初始化)自动管理堆分配内存的生命周期,当智能指针超出范围时释放资源。

std::unique_ptr

std::unique_ptr 实现资源的独占所有权的概念。它无法复制,只能移动(通过 std::move)。

C++
#include <memory>

// Recommended creation using std::make_unique (C++14)
std::unique_ptr<int> p1 = std::make_unique<int>(42);

// Accessing the resource like a normal pointer
std::cout << *p1 << std::endl;

// std::unique_ptr<int> p2 = p1; // COMPILER ERROR: copy not allowed!
std::unique_ptr<int> p2 = std::move(p1); // Allowed: p1 transfers ownership to p2

std::shared_ptr

std::shared_ptr 实现了共享所有权的概念。多个智能指针可以指向同一个资源。该类在内部维护一个引用计数:仅当最后一个活动的 shared_ptr 被销毁或重置时,才会释放内存。

C++
#include <memory>

std::shared_ptr<int> s1 = std::make_shared<int>(100);
std::shared_ptr<int> s2 = s1; // Allowed: increments the reference count

std::cout << s1.use_count() << std::endl; // Prints 2 (s1 and s2 share the resource)

自己尝试一下

锻炼#cpp.m7.l1.e1
尝试:0加载中...

声明一个名为 ptr 的 std::unique_ptr<int>,使用 std::make_unique 初始化它并保存值 42。使用 std::cout 打印 ptr 的取消引用值。

正在加载编辑器...
显示提示

使用 `std::unique_ptr<int> ptr = std::make_unique<int>(42);` ,然后将 `*ptr` 发送到输出流。

3 次尝试后可用的解决方案

锻炼#cpp.m7.l1.e2
尝试:0加载中...

使用 std::make_shared 实例化名为 ptr1 且值为 100 的 std::shared_ptr<int>。创建一个名为 ptr2 的副本,并使用 std::cout 打印 ptr1.use_count() 返回的值。

正在加载编辑器...
显示提示

复制是通过标准赋值完成的:“ptr2 = ptr1;”。 Printing `ptr1.use_count()` should display 2.

3 次尝试后可用的解决方案