RAII ใน C++
RAII (Resource Acquisition Is Initialization) เป็นเทคนิค C++ ที่ควบคุมวงจรชีวิตของทรัพยากร เป็นตัวแปรระดับและเชื่อมโยงกับเวลาชีวิตของวัตถุ
โดยสรุปทรัพยากรหลายอย่างไว้ในคลาสที่การจัดสรรทรัพยากรทำได้โดยตัวสร้างระหว่างการสร้างวัตถุและการจัดสรรคืนทรัพยากรจะทำโดยตัวทำลายล้างในระหว่างการทำลายวัตถุ
รับประกันทรัพยากรจนกว่าวัตถุจะมีชีวิตอยู่
ตัวอย่าง
void file_write {
Static mutex m; //mutex to protect file access
lock_guard<mutex> lock(m); //lock mutex before accessing file
ofstream file("a.txt");
if (!file.is_open()) //if file is not open
throw runtime_error("unable to open file");
// write text to file
file << text << stdendl;
} ตัวชี้อัจฉริยะในภาษา 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 de-referencing operator
T & operator * () {
return *p;
}
// Over loading 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