博客
关于我
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 配置清单(一篇够用)
查看>>
Nginx 配置解析:从基础到高级应用指南
查看>>
Nginx 集成Zipkin服务链路追踪
查看>>
nginx 集群配置方式 静态文件处理
查看>>
nginx+mysql+redis+mongdb+rabbitmq 自动化部署脚本
查看>>
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>
Nginx+Tomcat实现动静分离
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
nginx+vsftp搭建图片服务器
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
nginx: [emerg] getpwnam(“www”) failed 错误处理方法
查看>>
nginx: [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:
查看>>
nginx:Error ./configure: error: the HTTP rewrite module requires the PCRE library
查看>>
Nginx、HAProxy、LVS
查看>>
Nginx下配置codeigniter框架方法
查看>>
Nginx中使用expires指令实现配置浏览器缓存
查看>>
Nginx之二:nginx.conf简单配置(参数详解)
查看>>