이 튜토리얼에서는 C++에서 shared_ptr을 사용하여 가상 파괴를 이해하는 프로그램에 대해 논의할 것입니다.
클래스의 인스턴스를 삭제하기 위해 기본 클래스의 소멸자를 가상으로 정의합니다. 따라서 생성된 역순으로 상속된 다양한 개체 인스턴스를 삭제합니다.
예시
#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