Destructor ใน C++ จะถูกเรียกเมื่ออ็อบเจ็กต์ถูกทำลายและปล่อยหน่วยความจำกลับให้ระบบ เมื่อมีการโยนข้อยกเว้น (exception) ในคลาส Destructor จะถูกเรียกอัตโนมัติ ก่อนที่บล็อก catch จะถูกดำเนินการ
อัลกอริทึม
เริ่มต้น
ประกาศคลาส sample1
ประกาศ constructor ของ sample1
แสดง "Construct an Object of sample1"
ประกาศ destructor ของ sample1
แสดง "Destruct an Object of sample1"
ประกาศคลาส sample2
ประกาศ constructor ของ sample2
ประกาศตัวแปร i เป็น integer
กำหนด i = 7
แสดง "Construct an Object of sample2"
โยน i (throw i)
ประกาศ destructor ของ sample2
แสดง "Destruct an Object of sample2"
Try:
ประกาศอ็อบเจ็กต์ s1 ของคลาส sample1
ประกาศอ็อบเจ็กต์ s2 ของคลาส sample2
Catch(int i)
แสดง "Caught"
แสดงค่าของตัวแปร i
สิ้นสุด
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
class Sample1 {
public:
Sample1() {
cout << "Construct an Object of sample1" << endl;
}
~Sample1() {
cout << "Destruct an Object of sample1" << endl;
}
};
class Sample2 {
public:
Sample2() {
int i = 7;
cout << "Construct an Object of sample2" << endl;
throw i;
}
~Sample2() {
cout << "Destruct an Object of sample2" << endl;
}
};
int main() {
try {
Sample1 s1;
Sample2 s2;
} catch(int i) {
cout << "Caught " << i << endl;
}
}
ผลลัพธ์
Construct an Object of sample1 Construct an Object of sample2 Destruct an Object of sample1 Caught 7
สังเกต: Destructor ของ Sample2 ไม่ถูกเรียก เพราะ exception ถูกโยนใน constructor ก่อนที่อ็อบเจ็กต์จะสร้างเสร็จสมบูรณ์