技术

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 TypeIntroduced InDescription
std::auto_ptrC++98已废弃,复制会转移所有权std::auto_ptrC++98Deprecated, ownership transferred on copy
std::unique_ptrC++11独占所有权,不能复制std::unique_ptrC++11Unique ownership, non-copyable
std::shared_ptrC++11共享所有权,使用引用计数std::shared_ptrC++11Shared ownership via reference counting
std::weak_ptrC++11弱引用,不影响引用计数std::weak_ptrC++11Weak reference, avoids increasing ref count
std::make_sharedC++11高效构造 shared_ptrstd::make_sharedC++11Efficient shared_ptr creation
std::make_uniqueC++14安全构造 unique_ptrstd::make_uniqueC++14Safe 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_ptrshared_ptrweak_ptrauto_ptr
独占所有权
共享资源✅(弱引用)
自动释放资源
可复制✅(转移)
是否推荐使用✅ 推荐✅ 推荐✅ 推荐❌ 已废弃

🧾 五、总结

🧾 5. Summary

中文English
智能指针通过 RAII 机制管理堆内存资源,简化内存管理,防止泄漏,是现代 C++ 的核心。Smart pointers manage heap memory via RAII, simplifying resource management and preventing leaks — a core of modern C++.