Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Pointers, Smart Pointers และ Shared Pointers ใน C++

Pointers

Pointers ใช้เก็บที่อยู่ของตัวแปร

ไวยากรณ์

Type *pointer;

การเริ่มต้น

Type *pointer;
Pointer = variable_name;

หน้าที่

  • เก็บที่อยู่ของตัวแปร
  • สามารถกำหนดค่า null ได้
  • สามารถอ้างอิงได้โดย pass by reference
  • มีที่อยู่หน่วยความจำและขนาดของตัวเองบน Stack

ตัวอย่าง

#include <iostream>
using namespace std;

int main() {
    int a = 7;
    int *p = &a;
    cout << "Value of Variable: " << *p << endl;
    cout << "Address of Variable: " << p << endl;
    *p = 6;
    cout << "Value of the variable is now: " << *p << endl;
    return 0;
}

ผลลัพธ์

Value of Variable: 7
Address of Variable: 0x6ffe34
Value of the variable is now: 6

Smart Pointers ใน C++

Smart pointer เป็นชนิดข้อมูลนามธรรม ทำให้ pointer ธรรมดาจัดการหน่วยความจำได้อัตโนมัติ เช่น automatic destruction, reference counting

Implement เป็น template class overload * และ -> auto_ptr, shared_ptr, unique_ptr, weak_ptr เป็นรูปแบบที่ไลบรารีรองรับ

ตัวอย่าง

#include <iostream>
using namespace std;

template <class T>
class Smartpointer {
    T *p;
public:
    Smartpointer(T *ptr = NULL) { p = ptr; }
    ~Smartpointer() { delete(p); }
    T& operator * () { return *p; }
    T* operator -> () { return p; }
};

int main() {
    Smartpointer<int> p(new int());
    *p = 26;
    cout << "Value is: " << *p;
    return 0;
}

ผลลัพธ์

Value is: 26

Shared Pointers ใน C++

shared_ptr เป็นรูปแบบหนึ่งของ smart pointer เป็น container ของ raw pointer และโครงสร้าง reference counting (นับจำนวนอ้างอิง) แบบความเป็นเจ้าของร่วมกับทุก copies ของ shared_ptr

ออบเจ็กต์ที่ถูกอ้างอิงโดย raw pointer จะถูกทำลายก็ต่อเมื่อทุก copies ของ shared_ptr ถูกทำลาย

ตัวอย่าง

#include <iostream>
#include <memory>
using namespace std;

int main() {
    shared_ptr<int> ptr(new int(7));
    shared_ptr<int> ptr1(new int(6));
    cout << ptr << endl;
    cout << ptr1 << endl;
    cout << ptr.use_count() << endl;
    cout << ptr1.use_count() << endl;
    ptr.reset();
    cout << ptr.get() << endl;
    cout << ptr1.use_count() << endl;
    cout << ptr1.get() << endl;
    return 0;
}

ผลลัพธ์

0xe80900
0xe80940
1
1
0
1
0xe80940