📌 變數的記憶體通常會自動配置和自動釋放
有時候,需要在程式執行中動態建立資料
int* p = new int(10); // 配置記憶體
delete p; // 釋放記憶體
📌 如果忘了 delete,就會造成記憶體洩漏
長期執行下來,系統記憶體會越來越少
📌 不用再手動 delete
,記憶體會自動管理
類型 | 說明 | 特點 |
---|---|---|
unique_ptr |
獨佔所有權 | 不能被複製,只能轉移 |
shared_ptr |
共享所有權 | 多個指標可指向同一個物件 |
weak_ptr |
弱引用 | 不擁有物件,只能觀察 shared_ptr |
unique_ptr
#include <iostream>
#include <memory>
using namespace std;
int main()
{
unique_ptr<int> p = make_unique<int>(10);
cout << "數值:" << *p << endl;
unique_ptr<int> q = move(p);
if (!p)
cout << "p 已被轉移,現在是空的!" << endl;
cout << "q 的值:" << *q << endl;
return 0;
}
shared_ptr
的共享#include <iostream>
#include <memory>
using namespace std;
int main()
{
shared_ptr<int> a = make_shared<int>(42);
shared_ptr<int> b = a;
cout << "a 的值:" << *a << endl;
cout << "目前使用數:" << a.use_count() << endl;
b.reset();
cout << "b reset 後使用數:" << a.use_count() << endl;
return 0;
}
以前需要配置與釋放記憶體
容易出現洩漏或重複釋放的錯誤
現在有了智慧指標(unique_ptr
, shared_ptr
, weak_ptr
)
📌 讓記憶體自動釋放,不需人工管理