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

你可能感兴趣的文章
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
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
查看>>