Pointers
Pointers 代表一個物件在 Memory 的位置。其他的程式可以透過 Pointer 讀取該位置資料。
traditional pointers
int a = 1;
// Declaration
int* ptr = &a;
// print out the actual object inside the pointer
std::cout << *ptr << std::endl; // 1
// print out the address of the pointer
std::cout << ptr << std::endl; // 0x7ffd5268db54透過 Pointer 改變原本的物件
#include <iostream>
using namespace std;
int main() {
int a = 1;
int* ptr = &a;
std::cout << a << std::endl; // a is originally 1
// add the referenced object by 1
*ptr += 1;
// a is modified by ptr and becomes 2
std::cout << *ptr << std::endl;
std::cout << a << std::endl;
return 0;
}套用 Pointer 於 Functions 上
smart pointers
pointers 既是 c++ 的精髓,也是 c++ 的危險。不當的使用和一些的過失往往會導致 pointers 沒被清乾淨,被程式錯誤使用,最後導致程式崩潰。透過 smart pointers 可以幫助清理不被需要的 pointer 並加以管理正在使用的 pointer,使程式更安全。
unique pointer
這種 pointer 裡的物件只存在於它被定義的 scope,一旦離開就會自我刪除。這可以阻止 pointer 的共用,降低錯誤的風險。
shared pointer
這種 pointer 裡的物件在沒有 shared_ptr reference 的情況會自我刪除。這可以保護系統,使其回收不必要的 pointer,以降低錯誤的風險。
weak pointer
weak pointer 是一種 pointer,必須轉換成 shared_ptr 才能讀取資料。可以用於確保取得 reference 物件時物件存在。
Last updated