std::unique_ptr、std::shared_ptr和 std::weak_ptr。以下是详细使用方法:特点:同一时间只能有一个 unique_ptr指向对象,不可复 制但可移动。
适用场景:独占资源的场景(如工厂模式返回对象)。
基本用法:
#include<memory>
// 创建 unique_ptr
std::unique_ptr<int> ptr1 = std::make_unique<int>(42);// C++14 推荐
std::unique_ptr<int>ptr2(newint(100));// 传统方式
// 访问对象
*ptr1 =10;
std::cout <<*ptr1;// 输出 10
// 转移所有权(移动语义)
std::unique_ptr<int> ptr3 = std::move(ptr1);// ptr1 变为 nullptr自定义删除器(如文件句柄):
auto fileDeleter =[](FILE* f){if(f)fclose(f);};
std::unique_ptr<FILE,decltype(fileDeleter)>filePtr(fopen("test.txt","r"), fileDeleter);特点:多个指针共享同一对象,通过引用计数管理生命周期。
适用场景:需要多个所有者共享资源的场景。
基本用法:
// 创建 shared_ptr(推荐 make_shared)
auto ptr1 = std::make_shared<int>(42);
std::shared_ptr<int>ptr2(newint(100));// 不推荐(可能内存泄漏)
// 复 制增加引用计数
auto ptr3 = ptr1;// 引用计数 +1
// 手动查看引用计数
std::cout << ptr1.use_count();// 输出 2(ptr1 和 ptr3)自定义删除器:
auto deleter =[](int* p){delete p;};
std::shared_ptr<int>ptr(newint(42), deleter);循环引用问题:
structNode{
std::shared_ptr<Node> next;// 导致循环引用
};
auto a = std::make_shared<Node>();
auto b = std::make_shared<Node>();
a->next = b;
b->next = a;// 内存泄漏!解决方案:使用 std::weak_ptr。
特点:不增加引用计数,避免循环引用。
适用场景:打破 shared_ptr的循环依赖。
基本用法:
structNode{
std::weak_ptr<Node> next;// 弱引用解决循环问题
};
auto a = std::make_shared<Node>();
auto b = std::make_shared<Node>();
a->next = b;// weak_ptr 不增加引用计数
b->next = a;
// 访问 weak_ptr 需转为 shared_ptr
if(auto sharedPtr = a->next.lock()){
// 对象仍存在
}else{
// 对象已被销毁
}
示例代码:综合使用

输出:
Resource created
Resource created Use count: 2
Resource destroyed
Resource destroyed
通过合理使用智能指针,可显著提升 C++ 代码的安全性和可维护性。