在 Linux 下使用 C++ 时,智能指针(smart pointer) 是 C++ 标准库提供的一种自动管理动态内存(堆内存) 的工具,用来避免内存泄漏和悬空指针等问题。
传统写法(裸指针):
int* p = new int(10);
// 如果忘记 delete,或者中途 return / 抛出异常
delete p;
问题:
delete → 内存泄漏delete → 程序崩溃智能指针解决的问题:
✅ 自动释放内存
✅ 明确所有权
✅ 更安全、更易维护
Linux 下常用编译器(g++ / clang++)都支持:
| 智能指针 | 特点 | 使用场景 |
|---|---|---|
std::unique_ptr |
独占所有权 | 单一所有者 |
std::shared_ptr |
引用计数,共享所有权 | 多对象共享 |
std::weak_ptr |
不增加引用计数 | 解决循环引用 |
#include <memory>
std::unique_ptr<int> p = std::make_unique<int>(10);
// 自动释放
Linux 编译:
g++ test.cpp -std=c++14 -o test
shared_ptr 销毁时才释放内存#include <memory>
std::shared_ptr<int> p1 = std::make_shared<int>(10);
std::shared_ptr<int> p2 = p1; // 引用计数 +1
⚠️ 注意:避免循环引用
shared_ptrstd::shared_ptr<int> sp = std::make_shared<int>(10);
std::weak_ptr<int> wp = sp;
if (auto p = wp.lock()) {
// 安全使用
}
✅ 优先使用 make_unique / make_shared
✅ 尽量使用 unique_ptr
✅ 多线程中 shared_ptr 是线程安全的(控制块安全,对象不安全)
裸指针 → 手动管理(易出错)
unique_ptr → 独占(推荐)
shared_ptr → 共享(注意循环)
weak_ptr → 辅助 shared_ptr
如果你愿意,我也可以:
shared_ptr你想深入哪一块?