C++ 無內建垃圾回收 (GC),將記憶體管理權交給程式設計師換取極致效能。new 後忘記 delete 導致洩漏,是 C++ 最大陷阱。智慧指標透過 RAII 自動管理生命週期,成為標準解法。
| 缺陷 | 說明 |
|---|---|
| 獨佔所有權,不可複製 | 複製時轉移所有權,來源變空,極易導致邏輯錯誤 |
| 不支援陣列 | 無 auto_ptr<T[]>,delete[] 錯誤 |
| 不可放入 STL 容器 | 標準明確禁止,複製語意破壞容器不變量 |
| 無參考計數 | 無法共享所有權 |
| 類型 | 語意 | 適用場景 |
|---|---|---|
scoped_ptr | 不可複製、不可移動,單一擁有者 | 簡單 RAII,明確禁用複製 |
scoped_array | scoped_ptr 陣列版 | 陣列 RAII |
shared_ptr | 參考計數,共享所有權 | 多擁有者、複雜生命週期 |
shared_array | shared_ptr 陣列版 | 共享陣列 |
weak_ptr | 弱引用,不增加計數,打破循環引用 | 快取、觀察者、父子雙向引用 |
#include
auto p = std::make_unique(42);
auto arr = std::make_unique(100); // 正確 delete[]
// 移動語意轉移所有權
auto p2 = std::move(p); // p 變 nullptr
// 不可複製,編譯期保證
make_unique、C++20 make_unique_for_overwrite
auto sp1 = std::make_shared(); // 單次分配物件+控制塊
auto sp2 = sp1; // 計數+1
// 最後一個 shared_ptr 解構時 delete 物件
make_shared 效能優於 new T + shared_ptrweak_ptr 打破
std::weak_ptr cache_weak = cache_shared;
// 使用時鎖定
if (auto locked = cache_weak.lock()) {
locked->use();
} // 物件可能已銷毀
unique_ptr(預設首選)shared_ptrweak_ptrunique_ptr<T[]> 或 vectorunique_ptr/shared_ptrshared_ptr(new T) 兩次分配 → 用 make_sharedweak_ptr 打破unique_ptr 跨 DLL 邊界需統一 Deleter智慧指標是現代 C++ 記憶體安全的基石。拒絕裸 new/delete,擁抱 unique_ptr 為預設,按需升級 shared_ptr/weak_ptr,徹底終結記憶體洩漏。