C++ 智能指针总结
C++ Smart Pointers Summary (Chinese-English Bilingual)
📌 一、智能指针简介
📌 1. Introduction to Smart Pointers
中文 | English |
智能指针是封装原始指针的类,在对象生命周期结束时自动释放资源,防止内存泄漏。 | Smart pointers are wrapper classes for raw pointers that automatically release resources when no longer used, preventing memory leaks. |
📚 二、智能指针种类与版本
📚 2. Types and Version Introduced
智能指针类型 | 引入版本 | 简要说明 | Smart Pointer Type | Introduced In | Description |
std::auto_ptr | C++98 | 已废弃,复制会转移所有权 | std::auto_ptr | C++98 | Deprecated, ownership transferred on copy |
std::unique_ptr | C++11 | 独占所有权,不能复制 | std::unique_ptr | C++11 | Unique ownership, non-copyable |
std::shared_ptr | C++11 | 共享所有权,使用引用计数 | std::shared_ptr | C++11 | Shared ownership via reference counting |
std::weak_ptr | C++11 | 弱引用,不影响引用计数 | std::weak_ptr | C++11 | Weak reference, avoids increasing ref count |
std::make_shared | C++11 | 高效构造 shared_ptr | std::make_shared | C++11 | Efficient shared_ptr creation |
std::make_unique | C++14 | 安全构造 unique_ptr | std::make_unique | C++14 | Safe creation of unique_ptr |
🎯 三、各类型智能指针示例
🎯 3. Example Usage of Each Smart Pointer
✅ unique_ptr 独占所有权
✅ unique_ptr – Unique Ownership
std::unique_ptr<int> ptr = std::make_unique<int>(10);
// std::unique_ptr<int> ptr2 = ptr; ❌ 不可复制
std::unique_ptr<int> ptr2 = std::move(ptr); // ✅ 所有权转移
std::unique_ptr<int> ptr = std::make_unique<int>(10);
// std::unique_ptr<int> ptr2 = ptr; ❌ Copy not allowed
std::unique_ptr<int> ptr2 = std::move(ptr); // ✅ Ownership moved
✅ shared_ptr 共享所有权
✅ shared_ptr – Shared Ownership
std::shared_ptr<int> a = std::make_shared<int>(42);
std::shared_ptr<int> b = a; // 引用计数 +1
std::shared_ptr<int> a = std::make_shared<int>(42);
std::shared_ptr<int> b = a; // Reference count +1
✅ weak_ptr 弱引用,避免循环
✅ weak_ptr – Weak Reference (No Cycles)
std::shared_ptr<int> sp = std::make_shared<int>(100);
std::weak_ptr<int> wp = sp;
if (auto temp = wp.lock()) {
// 使用 temp 安全访问对象
}
std::shared_ptr<int> sp = std::make_shared<int>(100);
std::weak_ptr<int> wp = sp;
if (auto temp = wp.lock()) {
// Safe access to object via temp
}
⚠️ auto_ptr(已废弃)
⚠️ auto_ptr (Deprecated)
std::auto_ptr<int> p1(new int(10));
std::auto_ptr<int> p2 = p1; // 所有权转移
std::auto_ptr<int> p1(new int(10));
std::auto_ptr<int> p2 = p1; // Ownership transferred
🧠 四、指针功能对比
🧠 4. Smart Pointer Feature Comparison
功能/类型 | unique_ptr | shared_ptr | weak_ptr | auto_ptr |
独占所有权 | ✅ | ❌ | ❌ | ✅ |
共享资源 | ❌ | ✅ | ✅(弱引用) | ❌ |
自动释放资源 | ✅ | ✅ | ❌ | ✅ |
可复制 | ❌ | ✅ | ❌ | ✅(转移) |
是否推荐使用 | ✅ 推荐 | ✅ 推荐 | ✅ 推荐 | ❌ 已废弃 |
🧾 五、总结
🧾 5. Summary
中文 | English |
智能指针通过 RAII 机制管理堆内存资源,简化内存管理,防止泄漏,是现代 C++ 的核心。 | Smart pointers manage heap memory via RAII, simplifying resource management and preventing leaks — a core of modern C++. |