博客
关于我
delete对象时会自动调用类的析构函数
阅读量:410 次
发布时间:2019-03-06

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

一.背景

之前知道对象结束生命时,会自动调用析构函数.如果类中存在动态数组时,会在析构函数中会对动态数组对应的指针进行delete操作.不过一直对动态对象的delete操作和析构函数之间的关系没有太多关注.直到最近在看delete这块知识时,发现了这样的表述

二.举例

下面的代码中,在main函数的#if 1中动态创建了对象t,然后对t的成员变量进行了赋值,最后进行了delete t的操作.最后的执行结果是:

//运行结果 Object Releasep Release

这里实际上是delete操作做完后,就直接调用了析构函数.

 

而#else中写的是在栈中创建的对象t.该种情况下调用析构函数实际上是在main()函数的{}作用域结束后.

//实例代码 #define  _CRT_SECURE_NO_WARNINGS 1#include 
using namespace std;class Test{public: Test() { } ~Test() { cout << "Object Release" << endl; if (p) { delete p; p = NULL; cout << "p Release" << endl; } }public: char *p;};int main(){#if 1 Test *t = new Test(); t->p = new char[10]; strcpy(t->p, "hello"); delete t;#else Test t; t.p = new char[10]; strcpy(t.p, "hello");#endif return 0;}

 

转载地址:http://qnbkz.baihongyu.com/

你可能感兴趣的文章
nginx connect 模块安装以及配置
查看>>
nginx css,js合并插件,淘宝nginx合并js,css插件
查看>>
Nginx gateway集群和动态网关
查看>>
nginx http配置说明,逐渐完善。
查看>>
Nginx keepalived一主一从高可用,手把手带你一步一步配置!
查看>>
Nginx Location配置总结
查看>>
Nginx log文件写入失败?log文件权限设置问题
查看>>
Nginx Lua install
查看>>
nginx net::ERR_ABORTED 403 (Forbidden)
查看>>
vue中处理过内存泄露处理方法
查看>>
Nginx RTMP 模块使用指南
查看>>
Nginx SSL 性能调优
查看>>
nginx ssl域名配置
查看>>
Nginx SSL私有证书自签,且反代80端口
查看>>
Nginx upstream性能优化
查看>>
Nginx 中解决跨域问题
查看>>
nginx 代理解决跨域
查看>>
Nginx 做负载均衡的几种轮询策略分析
查看>>