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

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

背景

在C++编程中,对象结束其生命周期时,系统会自动调用析构函数(Destructor).当类中包含动态分配的内存时,析构函数会负责释放这些动态分配的内存。然而,长期以来,我一直对delete操作和析构函数之间的关系并没有深入了解。最近在学习delete相关知识时,我发现了一段有趣的描述:

举例

以下代码展示了两种情况:

如果 #if 1

// 代码片段Test *t = new Test();t->p = new char[10];strcpy(t->p, "hello");delete t;

运行结果会显示:

  • "Object Release" 被打印
  • "p Release" 也被打印

这表明,在执行delete操作后,系统立即调用了析构函数。

如果 #else

// 代码片段Test t;t.p = new char[10];strcpy(t.p, "hello");

在这种情况下,对象t是栈内存中的,因此不会使用delete操作.相反,当main函数结束时,系统会自动调用析构函数,释放内存.

总结

通过这两个例子可以看出,在栈中创建的对象和堆中创建的对象在内存释放上有显著的不同.堆中的对象需要手动调用delete,而栈中的对象则由系统自动释放.这种差异反映了内存管理的两种不同的方式,在编写高效和安全的C++代码时需要充分理解这些差异.

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

你可能感兴趣的文章
Oracle静默安装
查看>>
Oracle面试题:Oracle中truncate和delete的区别
查看>>
ThreadLocal线程内部存储类
查看>>
thinkphp 常用SQL执行语句总结
查看>>
Oracle:ORA-00911: 无效字符
查看>>
Text-to-Image with Diffusion models的巅峰之作:深入解读 DALL·E 2
查看>>
TCP基本入门-简单认识一下什么是TCP
查看>>
tableviewcell 中使用autolayout自适应高度
查看>>
Orcale表被锁
查看>>
svn访问报错500
查看>>
Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
查看>>
org.apache.ibatis.exceptions.PersistenceException:
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>