ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อเข้าใจการทำลายแบบ virtual (virtual destruction) โดยใช้ shared_ptr ใน C++
เพื่อลบอินสแตนซ์ของคลาสอย่างถูกต้อง เราต้องกำหนด destructor ของคลาสฐาน (base class) เป็น virtual ดังนั้นเมื่อลบออบเจกต์ผ่าน pointer ของคลาสฐาน จะเรียก destructor ของคลาสลูกก่อน ตามด้วยคลาสฐาน (ลำดับย้อนกลับจากการสร้าง)
ตัวอย่างโค้ด
#include <iostream>
#include <memory>
using namespace std;
class Base {
public:
Base() {
cout << "Constructing Base" << endl;
}
virtual ~Base() {
cout << "Destructing Base" << endl;
}
};
class Derived : public Base {
public:
Derived() {
cout << "Constructing Derived" << endl;
}
~Derived() {
cout << "Destructing Derived" << endl;
}
};
int main() {
std::shared_ptr<Base> sp{ new Derived };
return 0;
}
เอาต์พุต
Constructing Base Constructing Derived Destructing Derived Destructing Base