พอยน์เตอร์
พอยน์เตอร์ใช้สำหรับเก็บแอดเดรสของตัวแปร
ไวยากรณ์
Type *pointer;
การเริ่มต้น
Type *pointer; Pointer = variable name;
ฟังก์ชัน
- พอยน์เตอร์ใช้สำหรับเก็บที่อยู่ของตัวแปร
- พอยน์เตอร์สามารถกำหนดค่าว่างได้
- สามารถอ้างอิงพอยน์เตอร์ได้โดยใช้การอ้างอิง
- ตัวชี้มีที่อยู่หน่วยความจำและขนาดของตัวเองบนสแต็ก
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
// A normal integer variable
int a = 7;
// A pointer variable that holds address of a.
int *p = &a;
// Value stored is value of variable "a"
cout<<"Value of Variable : "<<*p<<endl;
// It will print the address of the variable "a"
cout<<"Address of Variable : "<<p<<endl;
// reassign the value.
*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
ตัวชี้อัจฉริยะใน C++
ตัวชี้อัจฉริยะเป็นประเภทข้อมูลนามธรรมโดยใช้ซึ่งเราสามารถสร้างตัวชี้ปกติในลักษณะที่สามารถใช้เป็นการจัดการหน่วยความจำ เช่น การจัดการไฟล์ ซ็อกเก็ตเครือข่าย ฯลฯ นอกจากนี้ยังสามารถทำอะไรได้หลายอย่าง เช่น การทำลายอัตโนมัติ การนับอ้างอิง เป็นต้น
ตัวชี้อัจฉริยะใน C ++ สามารถใช้เป็นคลาสเทมเพลตซึ่งมีตัวดำเนินการ * และ -> มากเกินไป auto_ptr, shared_ptr, unique_ptr และอ่อนแอ_ptr คือรูปแบบของตัวชี้อัจฉริยะที่สามารถนำมาใช้โดยไลบรารี C++
ตัวอย่าง
#include<iostream>
using namespace std;
// A generic smart pointer class
template <class T>
class Smartpointer {
T *p; // Actual pointer
public:
// Constructor
Smartpointer(T *ptr = NULL) {
p = ptr;
}
// Destructor
~Smartpointer() {
delete(p);
}
// Overloading dereferencing operator
T & operator * () {
return *p;
}
// Overloding arrow operator so that members of T can be accessed
// like a pointer
T * operator -> () {
return p;
}
};
int main() {
Smartpointer<int> p(new int());
*p = 26;
cout << "Value is: "<<*p;
return 0;
} ผลลัพธ์
Value is: 26
พอยน์เตอร์ที่แชร์ใน C++
shared_ptr เป็นหนึ่งในรูปแบบของตัวชี้อัจฉริยะที่สามารถนำมาใช้โดยไลบรารี C++ เป็นคอนเทนเนอร์ของพอยน์เตอร์ดิบและการนับการอ้างอิง (เทคนิคการจัดเก็บจำนวนการอ้างอิง พอยน์เตอร์ หรือแฮนเดิลไปยังทรัพยากร เช่น ออบเจกต์ บล็อกหน่วยความจำ พื้นที่ดิสก์ หรือทรัพยากรอื่นๆ) โครงสร้างความเป็นเจ้าของของพอยน์เตอร์ที่มีอยู่ร่วมกัน พร้อมสำเนาทั้งหมดของ shared_ptr.
อ็อบเจ็กต์ที่อ้างอิงโดยพอยน์เตอร์ดิบที่มีอยู่จะถูกทำลายก็ต่อเมื่อสำเนาทั้งหมดถูกทำลายจาก 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;
// Returns the number of shared_ptr objects
// referring to the same managed object.
cout << ptr.use_count() << endl;
cout << ptr1.use_count() << endl;
// Relinquishes ownership of ptr on the object
// and pointer becomes NULL
ptr.reset();
cout << ptr.get() << endl;
cout << ptr1.use_count() << endl;
cout << ptr1.get() << endl;
return 0;
} ผลลัพธ์
0xe80900 0xe80940 1 1 0 1 0xe80940