delete对象时会自动调用类的析构函数

一.背景

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

二.举例

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

//运行结果
Object Release p Release

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

 

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

//实例代码
#define
_CRT_SECURE_NO_WARNINGS 1 #include <iostream> 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; }

 

posted @ 2020-04-08 22:15  心媛意码  阅读(3730)  评论(0编辑  收藏  举报