博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[C++] Virtual Destructor(虚析构函数)
阅读量:7094 次
发布时间:2019-06-28

本文共 939 字,大约阅读时间需要 3 分钟。

 

 Without Virtual Destructor(虚析构函数)

class A{public:    int a = 3;    A()    {        cout <<"A()..."<< endl;    }     ~A()    {        cout << "~A()..." << endl;    }};class B : public A{public:    int b;    B(){        cout << "B()..." << endl;    }    ~B(){        cout << "~B()..." << endl;    }};void main(){    A *a = new B;    delete a;    system("pause");} result: A()... B()... ~A()... Press any key to continue . . . 没有~B(),内存泄漏!!

Virtual Destructor(虚析构函数)

class A{public:    int a = 3;    A()    {        cout <<"A()..."<< endl;    }    virtual ~A()    {        cout << "~A()..." << endl;    }};class B : public A{public:    int b;    B(){        cout << "B()..." << endl;    }    ~B(){        cout << "~B()..." << endl;    }};void main(){    A *a = new B;    delete a;    system("pause");} result:

 A()...

 B()...
 ~B()...
 ~A()...
 Press any key to continue . . .

防止内存泄漏!!

 

转载于:https://www.cnblogs.com/tianhangzhang/p/4966672.html

你可能感兴趣的文章
WebView使用配置文件
查看>>
深入浅出的javascript的正则表达式学习教程
查看>>
13 适配器
查看>>
在Linux上挂载Windows共享文件夹,如何开机自动挂载(mount)
查看>>
安装和使用cocoaPods
查看>>
Erlang学习: EUnit Testing for gen_fsm
查看>>
Android开发之多媒体编程之获取图片的副本
查看>>
nginx用户认证配置( Basic HTTP authentication)
查看>>
JavaScript与DOM(上)
查看>>
关于caffe-windows中 compute_image_mean.exe出现的问题
查看>>
技术人的未来(一)——跳槽
查看>>
asp.net 下载Excel (数据流,不保存)--客户端
查看>>
复习面向对象的OOA、OOD、OOP
查看>>
poj 2891 Strange Way to Express Integers(中国剩余定理)
查看>>
是男人就下100层【第五层】——2048游戏从源代码到公布市场
查看>>
算法:最长上升下降子序列
查看>>
F - The Circumference of the Circle
查看>>
S - 骨牌铺方格(第二季水)
查看>>
svn+ssh
查看>>
h264 profile & level
查看>>