RAII และ Cleanup แบบกำหนดแน่นอน
RAII cleanup อัตโนมัติทุกทางออกจาก scope รวม exception
RAII และ Cleanup แบบกำหนดแน่นอน คืออะไร?
RAII cleanup อัตโนมัติทุกทางออกจาก scope รวม exception
ผูก resource lifetime กับ object lifetime
ประเด็นสำคัญ
- เข้าใจกลไก C ก่อน abstraction ของ C++
- ใช้ RAII และ value semantics แสดง ownership
- เลือก abstraction ที่ type-safe แทน macro และ cast
ตัวอย่างโค้ด C และ C++
main.c
#include <stdio.h>
int main(void) {
int result = 1;
FILE *file = fopen("scores.txt", "w");
if (!file) goto cleanup;
if (fputs("Ada 95\n", file) < 0) goto cleanup;
result = 0;
cleanup:
if (file) fclose(file);
puts(result ? "failed" : "saved");
return result;
}
saved
C++
main.cpp
#include <fstream>
#include <iostream>
int main() {
std::ofstream file("scores.txt");
if (!file) return 1;
file << "Ada 95\n";
std::cout << "saved\n";
}
saved
เปรียบเทียบ C และ C++
C ใช้ cleanup label เพื่อไปถึง fclose ทุก path ส่วน fstream C++ ปิดใน destructor และทำ ownership ให้อยู่เฉพาะที่
C
C ใช้ prefix, callback, macro และ context struct
C++
ภาษาให้ abstraction ที่มี scope และ type-safe
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- เขียนกลไก C ก่อน
- แทน manual cleanup ด้วย RAII
- ตรวจ allocation และ virtual dispatch