ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อทำความเข้าใจการทำลายเสมือนโดยใช้ shared_ptr ใน C++
ในการลบอินสแตนซ์ของคลาส เรากำหนดให้ destructor ของคลาสพื้นฐานเป็นแบบเสมือน ดังนั้นมันจึงลบอินสแตนซ์ของอ็อบเจ็กต์ต่างๆ ที่สืบทอดมาในลำดับย้อนกลับที่สร้างขึ้น
ตัวอย่าง
#include <iostream>
#include <memory>
using namespace std;
class Base {
public:
Base(){
cout << "Constructing Base" << endl;
}
~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