博客
关于我
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/

你可能感兴趣的文章
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No static resource favicon.ico.
查看>>
no such file or directory AndroidManifest.xml
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>