在C ++中使用shared_ptr进行虚拟销毁
在本教程中,我们将讨论在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
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短